Maximum Subarray medium
Problem Statement
Find the contiguous subarray within a one-dimensional array (containing at least one number) which has the largest sum and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Example 2:
Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1.
Example 3:
Input: nums = [5,4,-1,7,8] Output: 23 Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
Steps
The problem can be solved efficiently using Kadane's Algorithm. The core idea is to maintain a current_max
variable that tracks the maximum sum ending at the current position. We also maintain a global_max
variable to store the overall maximum sum encountered so far.
- Initialization: Set
current_max
andglobal_max
to the first element of the array. - Iteration: Iterate through the array starting from the second element.
- Update
current_max
: For each element, decide whether to extend the current subarray (by adding the current element tocurrent_max
) or start a new subarray (by settingcurrent_max
to the current element). We choose the option that yields a larger sum. - Update
global_max
: Comparecurrent_max
withglobal_max
and updateglobal_max
ifcurrent_max
is larger. - Return: After iterating through the entire array, return
global_max
.
Explanation
Kadane's Algorithm cleverly avoids the need to explore all possible subarrays, which would lead to an O(n^2) time complexity. By iteratively building the current_max
, we efficiently find the optimal subarray. If current_max
becomes negative, it means that extending the current subarray would only decrease the sum, so it's better to start a new subarray from the next element.
Code
def max_sub_array(nums):
"""
Finds the maximum sum of a contiguous subarray.
Args:
nums: A list of integers.
Returns:
The maximum sum of a contiguous subarray.
"""
current_max = nums[0]
global_max = nums[0]
for i in range(1, len(nums)):
current_max = max(nums[i], current_max + nums[i])
global_max = max(global_max, current_max)
return global_max
Complexity
- Time Complexity: O(n), as we iterate through the array once.
- Space Complexity: O(1), as we use only a constant amount of extra space to store
current_max
andglobal_max
.