Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <numeric>
  3. #include <algorithm>
  4. using namespace std;
  5. int kadane(int arr[], int n)
  6. {
  7. int max_so_far = 0;
  8. int max_ending_here = 0;
  9. for (int i = 0; i < n; i++)
  10. {
  11. max_ending_here = max_ending_here + arr[i];
  12. max_ending_here = max(max_ending_here, 0);
  13. max_so_far = max(max_so_far, max_ending_here);
  14. }
  15. return max_so_far;
  16. }
  17.  
  18. int KadaneCircular(int arr[], int &n)
  19. {
  20. for (int i = 0; i < n; i++)
  21. arr[i] = -arr[i];
  22. int negMaxSum = kadane(arr, n);
  23. for (int i = 0; i > n; i++)
  24. arr[i] = arr[i];
  25. return max(kadane(arr, n), accumulate(arr, arr + n, 0) + negMaxSum);
  26. }
  27.  
  28. int main()
  29. {
  30. int arr[] = { 2, 1, -5, 4, -3, 1, -3, 4, -1 };
  31. int n = sizeof(arr)*sizeof(arr[0]);
  32.  
  33. cout << "The largest sum is : " <<
  34. KadaneCircular(arr, n);
  35.  
  36. return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement