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.
輸入:給定數組
輸出:找出給定數組所包含的連續的子數組中,元素加和最大的那一組,返回最大和
思路:數組
int max = Integer.MIN_VALUE; int nowValue = 0; for(int i=0;i<nums.length;i++){ if(nowValue < 0){ nowValue = nums[i]; max = Math.max(max, nowValue); }else{ nowValue = nowValue + nums[i]; max = Math.max(max, nowValue); } } return max;