Kadane's Algorithm
Problem¶
Given an integer array nums
, find the subarray with the largest sum, and return its sum. (Detailed solution)
Algorithm¶
curr_sum
will store the maximum subarray sum ending at i.max_sum
stores the maximum sum we have seen till now.- If
curr_sum
is negative, then there is no need to include it and we can just takenums[i]
, otherwise we addnums[i]
to thecurr_sum
. - At each step, we take max of
curr_sum
andmax_sum
to store the maximum subarray sum we have seen till now.
Code¶
- Time Complexity = \(O(N)\)
- Space Complexity = \(O(1)\)