Maximum sum in subArray
Problem to find the which subArray having Maximum sum and print the sum value.
Example-1:
Input : a = [ 5, 3, 1, -6, 2, 1] Output : 9 Explain : The subArray [5,3,1] has the maximum sum.
Example-2:
Input : a = [ 1, 2, -6, 9, 4, -6] Output : 13 Explain : The subArray [9,4] has the maximum sum.
Solution
public class Main { public static void main(String [] args) { int a [] = { 1, 2, -6, 9, 4,- 6}; int sum = a[0]; int final_sum = a[0]; for (int i = 1;i<a.length;i++) { if(sum + a[i] <= a[i]) { sum = a[i]; } else { sum += a[i]; } if(final_sum<sum) { final_sum = sum; } } System.out.print(final_sum); } }
Output
13