๐ฅLeetCode #53
nums
, find the subarray with the largest sum, and return its sum.Track current/overall maximum prefix:
int maxSum = nums[0];
int currentSum = nums[0];
Iterate through each element:
for(int i=1; i<nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + arr[i]);
maxSum = Math.max(currentSum, maxSum)
}
From the Math Class:

Solution:
You must understand Kadane's Algorithm to answer this, as you literally copy its format.
class Solution {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for(int i=1; i<nums.length;i++){
currentSum= Math.max(nums[i], currentSum+nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
}
Last updated
Was this helpful?