-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumSumSubArray.js
More file actions
51 lines (40 loc) · 1.11 KB
/
MaximumSumSubArray.js
File metadata and controls
51 lines (40 loc) · 1.11 KB
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
// given an integer array nums, find the subarray (containing at least one number) which has the largest sum and return its sum.
// Example 1: brute force
function maxSubarray1(nums) {
let maxSum = nums[0];
for (let i = 0; i < nums.length; i++) {
let currentSum = 0;
for (let j = i; j < nums.length; j++) {
currentSum += nums[j];
maxSum = Math.max(maxSum, currentSum);
}
}
return maxSum;
}
console.log(maxSubarray1([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6
// Example 2: Kadane's Algorithm
function maxSubarray2(nums) {
let maxSum = nums[0];
let currentSum = nums[0];
for (let i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(currentSum, maxSum);
}
return maxSum;
}
console.log(maxSubarray2([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6
function maxSubArray(nums) {
let sum = 0;
let max = nums[0];
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum > max) {
max = sum;
}
if (sum < 0) {
sum = 0;
}
}
return max;
}
console.log(maxSubarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6