A one-dimensional array with N integer elements (A[0], A[1]… A[n-2], A[n-1]), what is the maximum sum of the subarrays in an array (subarrays must be contiguous)? Example: The sum of the largest subarrays in A=[-2,5,3,-6,4,-8,6] is 8 (where 5+3=8). Please use dynamic programming method to solve, time complexity is O(n) algorithm thought: let B [j] represent the maximum sum of the subsequence ending with A [j] at the point j. Note: b[j] is not the sum of the largest contiguous subsequences in the preceding j-1 number, but only the sum of the largest contiguous subsequences containing a[j]. We find the maximum value in b[j], which is the sum of the maximum continuous subsequence. B [j]= Max {a[J],b[J-1]+a[j]}
function p (arr) {
let flag = arr[0];
let max = arr[0];
let l = arr.length;
for(let i = 1; i < l ; i ++) {
if(flag + arr[i] > arr[i]) {
flag += arr[i];
} else {
flag = arr[i];
}
max = Math.max(flag, max);
}
return max;
}
let temp = p([0, -2.3.5, -1.2]);
console.log(temp) / / 9
Copy the code