Advertisement
Vermiculus

MaxSubSum

Sep 30th, 2011
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. /**
  2.  * @author Sean Allred
  3.  * @author Molly Domino
  4.  *
  5.  */
  6. public class driver {
  7.  
  8.     // 2^n
  9.     private static int SubSum(int arr[]) {
  10.         int maxSum = 0;
  11.  
  12.         for (int startElement = 0; startElement < arr.length - 1; startElement++) {
  13.  
  14.             for (int endElement = startElement + 1; endElement < arr.length; endElement++) {
  15.  
  16.                 int thisSum = 0;
  17.                 for (int thisElementIndex = startElement; thisElementIndex <= endElement; thisElementIndex++) {
  18.  
  19.                     thisSum += arr[thisElementIndex];
  20.                 }
  21.  
  22.                 if (thisSum > maxSum)
  23.                     maxSum = thisSum;
  24.             }
  25.         }
  26.  
  27.         for (int i : arr)
  28.             if (i > maxSum)
  29.                 maxSum = i;
  30.  
  31.         return maxSum;
  32.  
  33.     }
  34.  
  35.     // n^3
  36.     public static int subSum(int arr[]) {
  37.         int maxSum = 0;
  38.         int thisSum = 0;
  39.         for (int startingElementIndex = 0;
  40.                  startingElementIndex < arr.length;
  41.                  startingElementIndex++) {
  42.             for (int endingElementIndex = arr.length;
  43.                      endingElementIndex > startingElementIndex;
  44.                      endingElementIndex--) {
  45.                 for (int thisElementIndex = startingElementIndex;
  46.                          thisElementIndex < endingElementIndex;
  47.                          thisElementIndex++) {
  48.                    
  49.                     thisSum += arr[thisElementIndex];
  50.                     if (thisSum > maxSum)
  51.                         maxSum = thisSum;
  52.                 }
  53.             }
  54.         }
  55.         return maxSum;
  56.     }
  57.  
  58.     private static int rand(java.util.Random r, int min, int max) {
  59.         return r.nextInt(max - min + 1) + min;
  60.     }
  61.  
  62.     public static void main(String[] args) {
  63.  
  64.         Integer s = Integer.parseInt(args[0]);
  65.  
  66.         int[] randArray = new int[s];
  67.  
  68.         java.util.Random randSeed = new java.util.Random();
  69.  
  70.         for (int i = 0; i < randArray.length; i++) {
  71.             randArray[i] = rand(randSeed, -10, 10);
  72.         }
  73.  
  74.         for (int T : randArray) {
  75.             System.out.println(T);
  76.         }
  77.  
  78.         System.out.print("Max Sum: " + SubSum(randArray));
  79.     }
  80.  
  81. }
  82.  
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement