Find the contiguous subarray with the largest sum, and return that sum.
Kadane's algorithm is one of the most frequently reused running-aggregate patterns in interviews.
"Maximum/minimum sum of a contiguous subarray" is Kadane's algorithm: at each position decide whether to extend the running subarray or restart from here.
Maintain `currentSum`, the best sum of a subarray ending exactly at the current index. At each element, `currentSum = max(nums[i], currentSum + nums[i])` — either the running subarray is still worth extending, or the current element alone is a better restart. Track the maximum `currentSum` seen across the whole scan as `bestSum`.
class Solution {
public int maxSubArray(int[] nums) {
int currentSum = nums[0];
int bestSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
bestSum = Math.max(bestSum, currentSum);
}
return bestSum;
}
}