题目:
输入一个整形数组,数组里有正数也有负数,数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度O(n)
解法:
动态规划问题
int greatestSubArraySum(int *arr, int len) {
if (arr == 0 || len <= 0) return -1;
int currSum = 0;
int greatestSum = 0x80000000;
for (int i = 0; i < len; ++i) {
if (currSum <= 0) {
currSum = arr[i];
} else {
currSum += arr[i];
}
if (currSum > greatestSum) {
greatestSum = currSum;
}
}
return greatestSum;
}