描述
给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。
注意事项
子数组最少包含一个数
样例
给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6
思考
- 子数组:数组中连续的数构成的数组(一开始以为是可以不连续的,结果就在排序求正值)
- 每到一个点都需要考虑是单独计算 还是 一起运算
- 需要有个值保存最大的结果
代码
// By Lentitude
class Solution {
public:
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
int maxSubArray(vector<int> nums) {
// write your code here
int temp = nums[0];
int ret = nums[0];
for( int i =1 ;i<nums.size(); i++) {
temp = max( nums[i] , nums[i] + temp );
ret = max( ret, temp);
}
return ret;
}
};
本文介绍了一种寻找整数数组中具有最大和的子数组的方法,并通过实例解释了该算法的工作原理。考虑到子数组必须由连续元素组成,文章提供了一个高效的解决方案。
824

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



