Skip to content

Instantly share code, notes, and snippets.

@sogwiz
Created July 10, 2019 18:21
Show Gist options
  • Save sogwiz/06a3f7506a0d2f91dc0315ded254f17d to your computer and use it in GitHub Desktop.
Save sogwiz/06a3f7506a0d2f91dc0315ded254f17d to your computer and use it in GitHub Desktop.
package com.learning.leet.strsarrs;
/**
* Created by sargonbenjamin on 7/10/19.
* https://leetcode.com/problems/maximum-subarray/
*/
public class MaximumSubarray {
public static void main(String args[]){
int[] arr = {-2,1,-3,4,-1,2,1,-5,4};
MaximumSubarray msm = new MaximumSubarray();
System.out.println(msm.maxSubArray(arr));
}
public int maxSubArray(int[] nums) {
if(nums==null || nums.length==0)return 0;
int prev = nums[0];
int max = prev;
for(int i = 1; i<nums.length; i++){
if(prev<0){
prev = 0;
}
prev+=nums[i];
if(prev>max)max = prev;
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment