Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [ − 2,1, − 3,4, − 1,2,1, − 5,4], the contiguous subarray [4, − 1,2,1] has the largest sum =
6.
public class MaximumSumSubarray {
public static void main(String[] args) {
int[] arr = {4,3,-2,6,-14,7,-1,4,5,7,-10,2,9,-10,-5,-9,6,1};
int maxSum =Integer.MIN_VALUE;
int tempSum = 0;
for(int i = 0;i< arr.length;i++){
tempSum+=arr[i];
if(tempSum<arr[i]){
tempSum = arr[i];
}
maxSum = Math.max(maxSum,tempSum);
}
System.out.println(maxSum);
}
}
No comments:
Post a Comment