-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum-subarray.ts
More file actions
29 lines (27 loc) · 822 Bytes
/
Copy pathmaximum-subarray.ts
File metadata and controls
29 lines (27 loc) · 822 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 53. Maximum Subarray (Medium)
* Link: https://leetcode.com/problems/maximum-subarray/
*
* Find the contiguous subarray with the largest sum and return that sum.
*
* Example:
* Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
* Output: 6 // [4, -1, 2, 1]
*
* Approach:
* Kadane's algorithm. Scan left to right keeping the best sum of a subarray
* ending at the current index: either extend the previous best or restart at
* the current element (whichever is larger). Track the global maximum.
*
* Time: O(n)
* Space: O(1)
*/
export function maxSubArray(nums: number[]): number {
let current = nums[0];
let best = nums[0];
for (let i = 1; i < nums.length; i++) {
current = Math.max(nums[i], current + nums[i]);
best = Math.max(best, current);
}
return best;
}