53. Maximum Subarray
Intitution
Complexity
Space Complexity
Time Complexity
Code
public int maxSubArray(int[] nums) {
// currentSum stores the sum of the current subarray
int currentSum = 0;
// maxSum keeps track of the maximum subarray sum found so far
int maxSum = Integer.MIN_VALUE;
// Iterate through all elements of the array
for (int i = 0; i < nums.length; ++i) {
// Add current number to the running sum
currentSum += nums[i];
// Update maxSum if currentSum is greater
maxSum = Math.max(currentSum, maxSum);
// If running sum is negative, reset it to 0
if (currentSum < 0) currentSum = 0;
}
// Return the maximum subarray sum found
return maxSum;
}
Last updated