DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Maximum sub array sum

Maximum sub array sum

tc : O(N), sc: O(1)

class Solution {
    public int maxSubArray(int[] nums) {
        //kadane approach
        int currentSum=0;
        int maxSum = Integer.MIN_VALUE;
        for(int i =0;i< nums.length;i++){
            currentSum+=nums[i];
            if(currentSum>maxSum){
                maxSum = currentSum;
            }
            if(currentSum<0) currentSum =0;
        }
        return maxSum;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)