Advertisement
rafikamal

Kadane's Algo

Jan 8th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. public class Solution {
  2.     public ArrayList<Integer> maxset(ArrayList<Integer> a) {
  3.         boolean positiveValueExists = false;
  4.         int maxValue = Integer.MIN_VALUE;
  5.        
  6.         for (int e : a) {
  7.             if (e >= 0) {
  8.                 positiveValueExists = true;
  9.                 break;
  10.             }
  11.            
  12.             maxValue = Math.max(e, maxValue);
  13.         }
  14.        
  15.         ArrayList<Integer> solution = new ArrayList<Integer>();
  16.         if (!positiveValueExists) {
  17.             solution.add(maxValue);
  18.             return solution;
  19.         }
  20.        
  21.         int maxSum = 0;
  22.         int maxSolutionLength = 0;
  23.         int maxSolutionStartingIndex = 0;
  24.        
  25.         int sum = 0;
  26.         int solutionLength = 0;
  27.         int startingIndex = 0;     
  28.  
  29.        
  30.         for (int i = 0; i < a.size(); i++) {
  31.             int e = a.get(i);
  32.            
  33.             sum += e;
  34.             solutionLength++;
  35.            
  36.             if (sum < 0) {
  37.                 sum = 0;
  38.                 solutionLength = 0;
  39.                 startingIndex = i + 1;
  40.             }
  41.             else {
  42.                 if (sum > maxSum || (sum == maxSum && solutionLength > maxSolutionLength)) {
  43.                     maxSum = sum;
  44.                     maxSolutionLength = solutionLength;
  45.                     maxSolutionStartingIndex = startingIndex;
  46.                 }
  47.             }
  48.         }
  49.        
  50.         return new ArrayList<Integer>(a.subList(maxSolutionStartingIndex,
  51.                 maxSolutionStartingIndex + maxSolutionLength));
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement