Skip to content

Commit ecea3e5

Browse files
authored
kadane_algo added in L-I (#51)
1 parent c3635d8 commit ecea3e5

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

L-I/0010 Kadanes_algorithm/README.md

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
Name : Aneesh
2+
Github username : 007aneesh
3+
Repository name : data-structures-and-algorithms
4+
Problem : Kadane's algorithm in Javascript
5+
Issue Number : #1182
6+
Problem statement : Given an integer array nums, find the subarray with the largest sum, and return its sum.
7+
8+
Sample testcases:
9+
10+
Testcase 1 -->
11+
12+
Input: number of elements in array = 9
13+
nums = [-2,1,-3,4,-1,2,1,-5,4]
14+
Output: 6
15+
16+
Testcase 2 -->
17+
Input: number of elements in array
18+
nums = [5,4,-1,7,8]
19+
Output: 23
20+
21+
Time Complexity = O(n)
22+
Space Complexity = O(n)
23+
24+
Explanation:
25+
This code asks the user to enter the number of elements in an array,
26+
and then prompts them to enter each element of the array one at a time.
27+
Once the array is complete, the code applies the Kadane's algorithm to
28+
find the maximum sum of any subarray within the array, and then prints
29+
the result to the console.
30+
31+
Kadane's algorithm is a way of finding the maximum sum of a contiguous subarray within an array,
32+
and it does so by keeping track of the maximum sum seen so far as it iterates through the array.
33+
At each step, it adds the current element to a running sum, and if that sum becomes negative,
34+
it resets the running sum to zero. If the running sum is ever greater than the maximum seen so far,
35+
it updates the maximum. Finally, it returns the maximum sum.
36+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// ----------------------------------------------------------------------------- code begins now!
2+
const readline = require("readline");
3+
4+
function kadaneAlgorithm(arr) {
5+
if (!arr) return 0;
6+
let sum = 0;
7+
let max = 0;
8+
9+
for (let i = 0; i < arr.length; i++) {
10+
max += arr[i];
11+
12+
if (max < 0) {
13+
max = 0;
14+
}
15+
16+
if (sum < max) {
17+
sum = max;
18+
}
19+
}
20+
21+
return sum;
22+
}
23+
24+
const rl = readline.createInterface({
25+
input: process.stdin,
26+
output: process.stdout,
27+
});
28+
29+
let arr = [];
30+
31+
rl.question("Enter number of elements in the array: ", function (n) {
32+
let count = 0;
33+
34+
function getArrayInput() {
35+
if (count < n) {
36+
rl.question("Enter element in array: ", function (input) {
37+
arr.push(Number(input));
38+
count++;
39+
getArrayInput();
40+
});
41+
} else {
42+
let ans = kadaneAlgorithm(arr);
43+
console.log(ans);
44+
rl.close();
45+
}
46+
}
47+
48+
getArrayInput();
49+
});

0 commit comments

Comments
 (0)