跳轉到

Kadane’s Algorithm

Given an array arr[] of size N. The task is to find the sum of the contiguous subarray within a arr[] with the largest sum.

function maxSubArraySum(nums) {
  let res = -Infinity;
  let curr = 0;
  let start = 0;
  let end = 0;

  let tmp;
  for (let idx = 0; idx < nums.length; idx++) {
    tmp = curr + nums[idx];

    if (tmp > nums[idx]) {
      curr = tmp;
    } else {
      start = idx;
      curr = nums[idx];
    }

    if (curr > res) {
      end = idx;
      res = curr;
    }
  }

  return res;
}