Implement Kadane max-sum subarray, prove correctness
Given an integer array nums, return the largest sum of a contiguous subarray.
For every nonempty nums the selected subarray must contain at least one element. The empty selection is not a candidate, so an all-negative array returns its largest element, which is the least negative value. The maximum over a nonempty collection of nonempty subarrays is always attained, so this answer always exists.
For an empty nums there is no nonempty subarray at all, and the contract reports 0. The empty array is the only input for which the empty selection is reported; every nonempty input is answered by a nonempty subarray.
Examples
Input: []
Output: 0
Input: [1]
Output: 1
Hints
Consider how Kadane's algorithm maintains a running sum and decides when to reset it, leveraging the optimal substructure property of the problem.
Prove correctness by induction: show that the algorithm's invariant (max sum ending at index i) holds for all i, and that the global maximum is correctly tracked.
Analyze edge cases (all negative numbers, single-element array) and explain why Kadane's algorithm handles them without additional modifications, using the recurrence relation `dp[i] = max(nums[i], dp[i-1] + nums[i])`.
Implement Kadane max-sum subarray, prove correctness
Given an integer array `nums`, return the largest sum of a contiguous subarray.