本次选择的题目是
Find the contiguous subarray within an array (containing at least one
number) which has the largest sum.For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous
subarray [4,-1,2,1] has the largest sum = 6.
Solution:
采用局部最优和全局最优解法:我们维护两个变量,一个是全局最优,就是到当前元素为止最优的解是,一个是局部最优,就是必须包含当前元素的最优的解。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if(nums.size() == 0){
return 0;
}
int global = nums[0];
int local = nums[0];
for(int i = 1; i < nums.size(); i++){
if(nums[i]>(local+nums[i])){
local = nums[i];
}else{
local = local+nums[i];
}
if(local > global){
global = local;
}
}
return global;
}
};