DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on

 

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 (3)

Collapse
 
lukeshiru profile image
Luke Shiru

Alternative approach making use of the functions available in JavaScript:

const maxSubArray = numbers =>
    Math.max(
        ...numbers.reduce(
            (sums, number) => sums.concat(Math.max(0, sums.at(-1) + number)),
            [0],
        ),
    );
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
 
rajeshroyal profile image
Rajesh Royal

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

Collapse
 
lukeshiru profile image
Luke Shiru

Not a fan of reduce, it just makes sense for this. For stuff like this, sums and multiplications, is better to use reduce.

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!