题目要求:
输入一个整型数组,有正数也有负数。数组中一个或连续的多个整数组成一个字数组。求所有子数组和的最大值。要求时间复杂度O(n).
leetcode | Maximum Subarray 最大连续子序列的和:
http://blog.csdn.net/quzhongxin/article/details/46603957
当前和是大于0,则对最大和是有贡献的,保留;
当前和是小于0,则对最大和是没有贡献的,舍弃;
#include <iostream>
#define INT_MIN 0x80000000
using namespace std;
int MaxSumSubArray(int nums[], int length) {
if (nums == NULL || length <= 0)
return 0;
int currentSum = 0;
int MaxSum = INT_MIN;
for (int i = 0; i < length; i++) {
if (currentSum <= 0) // 当前和小于0时,对最大和是没有贡献的
currentSum = nums[i];
else
currentSum += nums[i];
if (currentSum > MaxSum)
MaxSum = currentSum;
}
return MaxSum;
}
int main() {
int nums[] = {1,-2,3,10,-4,7,2,-5};
cout << MaxSumSubArray(nums, sizeof(nums)/sizeof(nums[0])) << endl;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-05 02:36:35