Advertisement
193030

Largest contiguous sum

May 8th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.52 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int maxSubArraySum(int a[], int size)
  5. {
  6.     int max_ending =0, max_so_far =0;
  7.     for(int i =0; i<size;i++)
  8.     {
  9.         max_ending = max_ending +a[i];
  10.         if(max_ending <0)
  11.             max_ending = 0;
  12.         if(max_ending>max_so_far)
  13.             max_so_far = max_ending;
  14.  
  15.     }
  16.     return max_so_far;
  17. }
  18.  
  19. int main()
  20. {
  21.     int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
  22.     int n = sizeof(a)/sizeof(a[0]);
  23.     int max_sum = maxSubArraySum(a, n);
  24.     cout << max_sum;
  25.     return 0;
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement