fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12.  
  13.  
  14. int []a = {-2, 1, -3, 4, -1, 2, 1, -5, 4 };
  15. int max_so_far = 0, max_ending_here = 0, index_max = 0;
  16. for(int i=0; i<a.length; i++) {
  17. max_ending_here = Math.max(0, max_ending_here + a[i]);
  18. if (max_so_far < max_ending_here) {
  19. max_so_far = max_ending_here;
  20. index_max = i;
  21. }
  22. }
  23. System.out.print("The maximal sum of subsequence is = "+max_so_far);
  24. int j = index_max;
  25. while (j >= 0 && max_so_far > 0) {
  26. max_so_far -= a[j--];
  27. }
  28. System.out.println(", from = "+(j+1)+" to "+index_max+", inclusive");
  29.  
  30.  
  31. }
  32. }
Success #stdin #stdout 0.04s 711168KB
stdin
Standard input is empty
stdout
The maximal sum of subsequence is = 6, from = 3 to 6, inclusive