DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on

4 1

maxSubArraySum in Javascript

We need to find the contiguous subarray sum which has the largest sum.

Example:

_

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
_

Here is the code:

function maxSubArray(nums) {
    let max = -Infinity;
    let sum = 0;
    for (let i = 0; i < nums.length; i++) {
        sum = sum + nums[i];
        if (max < sum) max = sum;
        if (sum < 0) sum = 0;
    }
    return max;
};
Enter fullscreen mode Exit fullscreen mode

Please provide any simplified solution you have.

Thanks.

Top comments (1)

Collapse
 
rajeshroyal profile image
Rajesh Royal

I see you are a big fan of reduce. This functional is pretty powerful.

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay