Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) with the largest sum and return its sum. This is known as the Maximum Subarray problem and is solved optimally with Kadane's algorithm, a classic example of dynamic programming.
Kadane's algorithm maintains two variables: the maximum sum ending at the current position, and the maximum sum seen so far. At each position, we decide whether to extend the current subarray or start a new one. The decision is: maxEndingHere = max(nums[i], maxEndingHere + nums[i]). This captures the optimal subarray ending at each position.
The DP recurrence is straightforward: the maximum subarray ending at position i is either the element itself (starting fresh) or the element plus the maximum subarray ending at position i-1 (extending). The answer is the maximum across all positions. This runs in O(n) time with O(1) space.
Edge cases include a single element (return that element), all negative numbers (return the largest negative), and an array with zeros and positives interleaved.
Kadane's algorithm is a classic example of DP where the subproblem is the maximum subarray ending at each position. By extending the best previous subarray or starting fresh, the algorithm explores all possible subarrays implicitly without enumerating them.
Example Input & Output
Single negative element.
Entire array sums to 23.
Subarray [4,-1,2,1] sums to 6.
Single element.
Entire array sums to 10.
Algorithm Flow

Solution Approach
Kadane's algorithm: track max sum ending here and max sum so far. Update both at each step.
Time O(n), Space O(1).
Best Answers
class Solution {
public int solution(int[] nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (int i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
