Given an array of integers (positive number with a negative number), to find the sum of the maximum number of consecutive columns, and returns the sum.
Example:
Input: [-2,1, -3,4, -1,2,1, -5,4]
Output: 6
Explanation: continuous subarray [4, -1,2,1], and the maximum was 6.
Problem-solving ideas:
Dynamic Programming: calculating the current index so far, and the largest continuous subarray, at this time, and max (a maximum before the current element subarray +, 0 + current element)
Code:
class Solution {
public int maxSubArray(int[] nums) {
int len=nums.length;
int max=nums[0];
for(int i=1;i<len;++i){
nums[i]+=Math.max(nums[i-1],0);
}
for(int i=0;i<len;++i){
if(max<nums[i]){
max=nums[i];
}
}
return max;
}
}