Guest User

Untitled

a guest
Jan 22nd, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. Algorithm MaxsubFaster(A):
  2. Input: An n-element array A of numbers, indexed from 1 to n.
  3. Output: The maximum subarray sum of array A.
  4. S0 ← 0 // the initial prefix sum
  5. for i ← 1 to n do
  6. Si ← Si−1 + A[i]
  7. m ← 0 // the maximum found so far
  8. for j ← 1 to n do
  9. for k ← j to n do
  10. s = Sk − Sj−1
  11. if s > m then
  12. m ← s
  13. return m
  14.  
  15. public static int maxSubFaster(int[] array)
  16. {
  17. Integer S[] = new Integer[array.length];
  18. Arrays.fill(S,0);
  19.  
  20. //initial prefix sum
  21. S[0] = 0;
  22. for (int i = 1; i < array.length; i++)
  23. {
  24. //S_i = S_i-1 + A[i]
  25. S[i] = S[i - 1] + array[i];
  26. }
  27. //maximum found so far
  28. int max = 0;
  29. for (int j = 1; j < array.length; j++)
  30. {
  31. for (int k = j; k < array.length; k++)
  32. {
  33. //s = S_k - S_j-1
  34. int s = S[k] - S[j - 1];
  35. //if s > m, m <- s
  36. if (s > max)
  37. {
  38. max = s;
  39. }
  40. }
  41. }
  42. return max;
  43. }//end maxSubFaster
Add Comment
Please, Sign In to add comment