Guest User

Untitled

a guest
Dec 14th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. package com.companyname.packagename;
  2.  
  3. import static java.lang.Math.max;
  4.  
  5. /**
  6. * Cracking the Coding Interview question 16.17 "Contiguous Sequence" on page 183.
  7. */
  8. public class ContiguousSequence
  9. {
  10. public static long maxSubArraySum(int[] arr)
  11. {
  12. if (arr == null)
  13. throw new NullPointerException();
  14. if (arr.length <= 0)
  15. throw new IllegalArgumentException("array cannot be empty");
  16.  
  17. long maxSubarraySum = arr[0];
  18. long maxSuffixSum = arr[0];
  19.  
  20. for (int i = 1; i < arr.length; i++) {
  21. maxSuffixSum = max(maxSuffixSum + arr[i], arr[i]);
  22. maxSubarraySum = max(maxSubarraySum, maxSuffixSum);
  23. }
  24.  
  25. return maxSubarraySum;
  26. }
  27. }
Add Comment
Please, Sign In to add comment