Skip to content

Commit 320ae85

Browse files
committed
added the max sum subarray problem solution
1 parent 6ad3ca2 commit 320ae85

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

MaxSumSubarray.js

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
2+
// Brute Force approach
3+
function find_maximum_subarray(arr, length) {
4+
/*write the code to find the maximum subarray sum
5+
Both array and size of array is given */
6+
7+
let max_sum = arr[0];
8+
for (let i = 0; i < length; i++) {
9+
let curr_sum = 0;
10+
for (let j = i; j < length; j++) {
11+
curr_sum += arr[j];
12+
if (curr_sum > max_sum) max_sum = curr_sum;
13+
}
14+
}
15+
return max_sum;
16+
}
17+
18+
console.log(find_maximum_subarray([5, 2, -4, -5, 3, -1, 2, 3, 1], 9));
19+
20+
21+
22+
// Kadane's Algorithm
23+
24+
// The idea of Kadane’s algorithm is to maintain a variable max_ending_here that stores the
25+
// maximum sum contiguous subarray ending at current index and a variable max_so_far stores the
26+
// maximum sum of contiguous subarray found so far, Everytime there is a positive-sum value
27+
// in max_ending_here compare it with max_so_far and update max_so_far if it is greater than
28+
// max_so_far.
29+
30+
// So the main Intuition behind Kadane’s Algorithm is,
31+
32+
// 1. The subarray with negative sum is discarded (by assigning max_ending_here = 0 in code).
33+
// 2. We carry subarray till it gives positive sum.
34+
35+
36+
37+
function find_maximum_subarray(arr, length) {
38+
39+
let max_sum = arr[0];
40+
let sum = 0;
41+
for (let i = 0; i < length; i++) {
42+
sum = sum + arr[i];
43+
if (sum > max_sum) max_sum = sum;
44+
if (sum < 0) sum = 0;
45+
}
46+
return max_sum;
47+
}
48+
49+
console.log(find_maximum_subarray([5, 2, -4, -5, 3, -1, 2, 3, 1], 9));

0 commit comments

Comments
 (0)