Skip to content

Files

Latest commit

 

History

History
19 lines (15 loc) · 813 Bytes

Maximum Subarray.md

File metadata and controls

19 lines (15 loc) · 813 Bytes

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

A subarray is a contiguous part of an array.

Screen Shot 2021-11-01 at 6 44 34 PM

Time complexityL O(n) -- Hashmap solution

var maxSubArray = function(nums) {
    let prev = 0;
    let max = -Infinity;
    for(let i = 0; i < nums.length; i++) {
        prev = Math.max(prev + nums[i], nums[i]);//prev will check if the upcoming number is larger than current number plus itself
        max = Math.max(max, prev);//  max will always keep the maximum number, because prev may smaller than max
    }
    return max
};