DEV Community

Matan Shaviro
Matan Shaviro

Posted on • Edited on

LeetCode: Max subArray sum

Suppose we are given the following array, and the Fixed Size is 3. We need to find the Sub Array with the highest sum.
Image description

Now, we will iterate through 3 elements in the array at a time, calculate their sum, and compare it with the value in maxSum, where we will store the maximum sum found so far during the search.
Image description

The next 3 values give us a result of 9, which is indeed greater than 8.
Therefore, we will update maxSum to the new value.
Image description

We will continue using this Sliding Window method until we reach the last triplet in the array, ensuring we have processed all the values.

Now, let’s look at the code with two example cases, each using a different fixed size:

function maxSubArray(nums, size) {
  let currentSum = 0
  let maxSum = 0

  for (let i = 0; i < nums.length; i++) {
    currentSum += nums[i]
    if (i >= size - 1) {
      maxSum = Math.max(currentSum, maxSum)
      currentSum -= nums[i - (size - 1)]
    }
  }
  return maxSum
}

let inputArray = [2, 3, 4, 1, 5]
let size = 2
console.log(maxSubArray(inputArray, size)) // Output: 7

inputArray = [2, 3, 4, 1, 5]
size = 3
console.log(maxSubArray(inputArray, size)) // Output: 10

Enter fullscreen mode Exit fullscreen mode

Top comments (0)