ginsul

Untitled

Nov 7th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. public class ArraySum {
  2.  
  3.     public static void main(String[] args) {
  4.         int[] inputArray = {-2,1,-3,4,-1,2,1,-5,4};
  5.         int [] result = subArraySum(inputArray);
  6.         System.out.println("Max sum: " + result[0] + ", maxSumLowerBound: " + result[1] + ", maxSumHigherBound: " + result[2]);
  7.     }
  8.  
  9.     private static int[] subArraySum(int[] inputArray) {
  10.         int arraylength = inputArray.length;
  11.         int maxSum = Integer.MIN_VALUE;
  12.         int maxSumLowerBound = -1;
  13.         int maxSumHigherBound = -1;
  14.  
  15.         for (int i = 0; i < arraylength; i++) {
  16.             int sum = 0;
  17.             for (int j = i; j < arraylength; j++) {
  18.                 sum += inputArray[j];
  19.                 if (sum > maxSum) {
  20.                     System.out.println("old sum: " + maxSum + ", new sum: " + sum + ", maxSumLowerBound: " + i + " , maxSumHigherBound: " + j);
  21.                     maxSum = sum;
  22.                     maxSumLowerBound = i;
  23.                     maxSumHigherBound = j;
  24.                 }
  25.             }
  26.         }
  27.  
  28.         return new int[]{maxSum, maxSumLowerBound, maxSumHigherBound};
  29.     }
  30.  
  31.  
  32. }
Advertisement
Add Comment
Please, Sign In to add comment