Optimal Dynamic Programming Approach (Kadane's Algorithm):
- Track the maximum sum ending at the current index, either extending the previous subarray or starting fresh.
def max_sub_array(nums: list[int]) -> int:
max_so_far = nums[0]
current_sum = nums[0]
for x in nums[1:]:
current_sum = max(x, current_sum + x)
max_so_far = max(max_so_far, current_sum)
return max_so_far
Complexity & Key Logic:
- Time Complexity: O(N) single pass through the array.
- Space Complexity: O(1) using two scalar variables.
- Algorithm Details:
- At each index, decide whether to append the current element x to the running sum (current_sum + x) or discard negative accumulated debt and start a new subarray at x (max(x, current_sum + x)).
- Update max_so_far whenever current_sum exceeds the previous record.
- Correctly handles arrays where all numbers are negative by picking the least negative single element.