Back to Dashboard
Maximum Subarray
MediumProblem Statement
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Examples
Example 1:
- Input: nums = [1,2,3,4]
- Output: 10
Approach 1: Optimal
O(n)
O(1)
class Solution {
public int maxSubArray(int[] nums) {
var currentMax = nums[0];
var max = nums[0];
for (int i = 1; i < nums.length; i ++) {
if (currentMax < 0) { // negative sum won't contribute to the maximum sum
currentMax = 0;
}
currentMax += nums[i];
max = Math.max(currentMax, max);
}
return max;
}
}