-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy path0053. Maximum Subarray.js
79 lines (73 loc) · 1.72 KB
/
0053. Maximum Subarray.js
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest currMax and return its currMax.
//
// Example:
//
// Input: [-2,1,-3,4,-1,2,1,-5,4],
// Output: 6
// Explanation: [4,-1,2,1] has the largest currMax = 6.
//
// Follow up:
//
// If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
/**
* @param {number[]} nums
* @return {number}
*/
// 1) Brute force (time limit exceeded)
// Time O(n^3)
// Space O(1)
const maxSubArray1 = (nums) => {
let max = -Infinity;
for (let i = 0; i < nums.length; i++) {
for (let j = i; j < nums.length; j++) {
let sum = 0;
for (let k = i; k <= j; k++) {
sum += nums[k];
}
if (sum > max) max = sum;
}
}
return max;
};
// 2) Dynamic programming - Kadane's algorithm
// Similar
// 152. Maximum Product Subarray
//
// Time O(n)
// Space O(1)
//
// Idea
// Suppose we've solved the problem for A[1 .. i - 1]; how can we extend that to A[1 .. i]?
//
// Example
// 5 -12 10
//
// 5
// 5
// -7
// 5
// 10 (recalculate from nums[i])
// 10
const maxSubArray2 = (nums) => {
let currMax = nums[0];
let max = nums[0];
for (let i = 1; i < nums.length; i++) {
currMax = Math.max(currMax + nums[i], nums[i]); // if nums[i] is bigger, recalculate from nums[i]
max = Math.max(max, currMax);
}
return max;
};
// 3) Similar to 2
const maxSubArray = (nums) => {
let currMax = -Infinity;
let max = -Infinity;
for (let i = 0; i < nums.length; i++) {
if (nums[i] + currMax < nums[i]) {
currMax = nums[i];
} else {
currMax += nums[i];
}
max = Math.max(max, currMax);
}
return max;
};