Advertisement
Guest User

Untitled

a guest
Oct 8th, 2015
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. static int maxSubArray(int[] array){
  2. // We make a new array to store the sum of the maximal subarray up till that index in the original array
  3. int[] B = new int[array.length];
  4. // A subarray of length 0 has a value of 0
  5. B[0] = Math.max(array[0], 0);
  6.  
  7. /* The maximal starts at 0, because you can always have a subarray that has a length of 0
  8. * making the value 0 (even if the subarrays with length equal or bigger than 1 have negative values).
  9. */
  10. int max = B[0];
  11.  
  12. // We loop through every element in the original array
  13. for(int i = 1; i < array.length; i++){
  14. /* The sum of the maximal subarray at index i is maximal value of:
  15. * the sum of an empty subarray (0) or the sum of maximal subarray at index i - 1 and the value at index i.
  16. * Because you store the maximal sum of subarrays for every index, you can use these to calculate the sum of subarrays containing
  17. * elements at higher indices.
  18. */
  19. B[i] = Math.max(0, B[i - 1] + array[i]);
  20. /* the new maximal value is either the maximal value over all, or (if the value at B[i]) is bigger than the max up till then) B[i]
  21. *
  22. */
  23. max = Math.max(max, B[i]);
  24. }
  25. // In the end you return the max value
  26. return max;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement