题目描述:
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
中文理解:寻找出一个数组中和最大的子数组连续序列。
解题思路:寻找子最大的数组,可以找出这样的规律,设置前面的sum为前面的子数组的和最大值,同时设置一个全局的最大值global,sum去max(sum,sum+nums[i]),同时如果取了sum为最大值,则连续数组断了,故需要使用global保存全局的序列最大值,最后输出global即可
代码(java):
class Solution {
public int maxSubArray(int[] nums) {
if(nums.length==0)return 0;
int sum=0;
int global=Integer.MIN_VALUE;
for(int num : nums){
sum=Math.max(num,num+sum);
global=Math.max(sum,global);
}
return global;
}
}