题目
给定一个整数数组,数组里可能有正数、负数和零。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。例如,如果输入的数组为{1,-2,3,10,-4,7,2,-5},那么和为最大的连续子数组为{3,10,-4,7,2},和为18。
思路
使用动态规划的思想。令currSum是以当前元素结尾的最大连续子数组的和,maxSum是全局的最大子数组的和,当往后扫描时,对第i个元素有两种选择,要么放入前面找到的子数组,要么作为新子数组的第一个元素:如果currSum>0,则令currSum加上array[i];如果currSum<=0,则currSum被置为当前元素,即currSum=array[i]。而对于maxSum,则若maxSum < currSum,则更新maxSum=currSum,否则maxSum保持原值,不更新。
代码
//
// Created by huxijie on 17-3-18.
// 最大连续子数组的和
#include <iostream>
using namespace std;
int MaxSubArraySum(int array[],int n) {
int from,to; //记录所求子数组的首尾下标
int curSum = 0, maxSum = 0;
for (int i = 0; i < n; ++i) {
if (curSum > 0) {
curSum += array[i];
if (maxSum < curSum) {
to = i;
maxSum = curSum;
}
} else {
curSum = array[i];
if (maxSum < curSum) {
from = i;
maxSum = curSum;
}
}
}
int j;
for (j = from; j < to ; ++j) {
cout<<array[j];
if (array[j + 1] >= 0) {
cout << "+";
}
}
cout << array[j] << "=" << maxSum << endl;
}
int main() {
int n =8;
int array[] = {1, -2, 3, 10, -4, 7, 2, -5};
MaxSubArraySum(array, n);
return 0;
}
运行结果
3+10-4+7+2=18
Process finished with exit code 0
本文介绍了一种利用动态规划思想解决最大连续子数组和问题的方法。通过对数组进行遍历,并根据当前元素决定是否加入到已有的子数组中,从而找出具有最大和的连续子数组。
382

被折叠的 条评论
为什么被折叠?



