Largest Sum Subarray - Coderust_ Hacking the Coding Interview
Largest Sum Subarray - Coderust_ Hacking the Coding Interview
• Description
• Hints
• Try it yourself
• Solution
• Runtime complexity
• Memory complexity
Description #
In the array below, the largest sum subarray starts at index 3 and ends at
6 , and with the largest sum being 12.
-4 2 -5 1 2 3 6 -5 1
Hints #
Use Kadane’s algorithm.
Try it yourself #
C++ Java Python JS Ruby
https://www.educative.io/courses/coderust-hacking-the-coding-interview/kWpK 1/4
02/11/2020 Largest Sum Subarray - Coderust: Hacking the Coding Interview
Solution #
Runtime complexity #
The runtime complexity of this solution is linear, O(n).
Memory complexity #
The memory complexity of this solution is constant, O(1).
The basic idea of Kadane’s algorithm is to scan the entire array and at
each position find the maximum sum of the subarray ending there. This is
achieved by keeping a current_max for the current array index and a
global_max . The algorithm is as follows:
current_max = A[0]
global_max = A[0]
for i = 1 -> size of A
if current_max is less than 0
then current_max = A[i]
otherwise
current_max = current_max + A[i]
if global_max is less than current_max
then global_max = current_max
Initial state -4 2 -5 1 2 3 6 -5 1
current_max = -4 global_max = -4
1 of 10
https://www.educative.io/courses/coderust-hacking-the-coding-interview/kWpK 2/4
02/11/2020 Largest Sum Subarray - Coderust: Hacking the Coding Interview
The solution below only finds the maximum contiguous sum in the
array; however, it can easily be modified to track the starting and
ending indexes of this subarray.
return global_max;
}
int main() {
Back Next
Mark as Completed
https://www.educative.io/courses/coderust-hacking-the-coding-interview/kWpK 3/4
02/11/2020 Largest Sum Subarray - Coderust: Hacking the Coding Interview
23% completed, meet the criteria and claim your course certi cate! Buy Certificate
Ask a Question
Report an
(https://discuss.educative.io/tag/largest-sum-subarray__dynamic-
Issue
programming__coderust-hacking-the-coding-interview)
https://www.educative.io/courses/coderust-hacking-the-coding-interview/kWpK 4/4