forked from NKaty/Algorithms-and-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum-subarray.js
More file actions
32 lines (25 loc) · 1003 Bytes
/
maximum-subarray.js
File metadata and controls
32 lines (25 loc) · 1003 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
30
31
32
// Given an integer array nums, find the contiguous subarray
// (containing at least one number) which has the largest sum and return its sum.
// Time Complexity O(n)
// Space Complexity O(n)
function maxSubArray(nums) {
const subArraySum = [nums[0]];
for (let i = 1; i < nums.length; i++) {
subArraySum.push(Math.max(nums[i] + subArraySum[i - 1], nums[i]));
}
return Math.max(...subArraySum);
};
console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6
console.log(maxSubArray([-1, 0, -2])); // 0
console.log(maxSubArray([-1])); // -1
// Time Complexity O(n)
// Space Complexity O(1)
function maxSubArrayWithoutAdditinalSpace(nums) {
for (let i = 1; i < nums.length; i++) {
nums[i] = Math.max(nums[i] + nums[i - 1], nums[i]);
}
return Math.max(...nums);
};
console.log(maxSubArrayWithoutAdditinalSpace([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6
console.log(maxSubArrayWithoutAdditinalSpace([-1, 0, -2])); // 0
console.log(maxSubArrayWithoutAdditinalSpace([-1])); // -1