javascript 子阵-W-MAX-总和

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 子阵-W-MAX-总和相关的知识,希望对你有一定的参考价值。

// Please find the subarray with maximal sum (a) - linear solution, (b) - using prefix sums approach

function maxSumSubarray(arr) {
  let n = arr.length;
  // init min prefix sum to 0.
  let min_prefix_sum = 0;

  // initialize min subarray sum so far to -infinity.
  let res = -Infinity;

  // init and compute the prefix sum array.
  let prefix_sum = [];
  prefix_sum[0] = arr[0];
  for (let i = 1; i < n; i++) {
    prefix_sum[i] = prefix_sum[i - 1] + arr[i];
  }

  // loop through the array, keep 
  // track of min prefix sum so 
  // far and max subarray sum.
  for (let i = 0; i < n; i++) {
    res = Math.max(res, prefix_sum[i] - min_prefix_sum);
    min_prefix_sum = Math.min(min_prefix_sum, prefix_sum[i]);
  }

  return res;
}


  let arr1 = [ -2, -3, 4, -1, -2, 1, 5, -3 ];
  console.log(maxSumSubarray(arr1));


  let arr2 = [ 4, -8, 9, -4, 1, -8, -1, 6 ];
  console.log(maxSumSubarray(arr2));



function maxSubArrSum(a) {
  let max_so_far = a[0];
  let curr_max = a[0];

  for (let i = 1; i < a.length; i++) {
    curr_max = Math.max(a[i], curr_max + a[i]);
    max_so_far = Math.max(max_so_far, curr_max);
  }
  return max_so_far;
}
console.log(maxSubArrSum(arr1));
console.log(maxSubArrSum(arr2));

以上是关于javascript 子阵-W-MAX-总和的主要内容,如果未能解决你的问题,请参考以下文章

最大子阵和

空间谱专题11:子阵平滑与秩亏缺

最大子阵

历届试题 最大子阵

试题 历届试题 最大子阵(dp)

试题 历届试题 最大子阵(dp)