Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

js how to get max sub array sum

let arr = [-11, 15, -9, -2, -3, -5, 8];

const checkArr = (/** @type {number[]} */ arr) => arr.every((/** @type {number} */ elem) => elem < 0);

/**
 * @param {number[]} arr
 */
function getMaxSubSum(arr) {
  let maxSum = 0;
  let currentSum = 0;

  if (checkArr(arr)) return 0;

  for (let i = 0; i < arr.length; ++i) {
    currentSum = Math.max(arr[i], currentSum + arr[i]);

    maxSum = Math.max(currentSum, maxSum);
  }

  return maxSum;
}

console.log(getMaxSubSum(arr));
Source by medium.com #
 
PREVIOUS NEXT
Tagged: #js #max #array #sum
ADD COMMENT
Topic
Name
8+6 =