Maximum Subarray.md
December 10, 2025 ยท View on GitHub
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.
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
};