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. int[] arr = {6, 4, -2, -8, 1};
  13. int sum = findMaxSum(arr);
  14. System.out.println(sum);
  15. }
  16. public static int findMaxSum(int arr[]) {
  17. if (arr.length == 0) return 0;
  18. if (arr.length == 1) return arr[0];
  19. int a = arr[0];
  20. int b = Math.max(arr[0], arr[1]);
  21. int c = b;
  22.  
  23. for(int i=2; i<arr.length; i++) {
  24. c = Math.max(arr[i], Math.max(b, arr[i] + a));
  25. a = b; // a now becomes second last sum
  26. b = c; // b now becomes previous sum
  27. }
  28.  
  29. return c;
  30. }
  31. }
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
7