Skip to content

Commit 1f898d0

Browse files
committed
add explanation and time space complexity
1 parent dac8ea8 commit 1f898d0

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

Famous Algorithms/kadanes.go

+24-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
11
/*
2-
Write a function that takes in a non-empty array of integers and returns the
3-
maximum sum that can be obtained by summing up all of the integers in a
4-
non-empty subarray of the input array. A subarray must only contain adjacent
5-
numbers (numbers next to each other in the input array).
2+
Write a function that takes in a non-empty array of integers and returns the
3+
maximum sum that can be obtained by summing up all of the integers in a
4+
non-empty subarray of the input array. A subarray must only contain adjacent
5+
numbers (numbers next to each other in the input array).
6+
7+
Sample Input: [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]
8+
Output: 19
9+
10+
Explanation:
11+
12+
The function takes an array of integers as input, and initializes two variables: `maxEndingHere` and `maxSoFar`.
13+
`maxEndingHere` keeps track of the maximum subarray sum that ends at the current element, and `maxSoFar` keeps track
14+
of the maximum subarray sum seen so far.
15+
16+
The function then iterates through the array starting at the second element, and for each element, it calculates the
17+
maximum subarray sum that ends at that element by adding the current element to the maximum subarray sum that ends at
18+
the previous element (`maxEndingHere + num`). If this sum is greater than the current element itself (`num`), then `maxEndingHere` is updated to the sum. Otherwise, `maxEndingHere` is updated to `num`.
19+
20+
After each iteration, `maxSoFar` is updated to the maximum value seen so far, which is either `maxEndingHere` or `maxSoFar`.
21+
22+
The function finally returns `maxSoFar`, which represents the maximum subarray sum of the input array. The `max` function
23+
is a helper function used to compare two integers and return the maximum of the two.
24+
25+
O(n) time | O(1) space - where n is the length of the input array
626
727
*/
828
package main

0 commit comments

Comments
 (0)