Advertisement
-LIR-

Kadane

Jul 19th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <time.h>
  5.  
  6. using namespace std;
  7.  
  8. int n, v[1000], aux, MAX, END, length[1000];
  9.  
  10. int main()
  11. {
  12.     srand(time(NULL));
  13.  
  14.     cout << "Find the subarray with the biggest sum in a given array.\n";
  15.     cin >> n;
  16.     for( int i=1 ; i<=n ; i++)
  17.     {
  18.         v[i] = rand() % 21 - 10;
  19.         cout << v[i] << " ";
  20.     }
  21.     aux = v[1];
  22.     length[1] = 1;
  23.     MAX = aux;
  24.     END = 1;
  25.     for( int i=2 ; i<=n ; i++ )
  26.     {
  27.         if( v[i] > aux + v[i] )
  28.         {
  29.             aux = v[i];
  30.             length[i] = 1;
  31.         }
  32.         else
  33.         {
  34.             aux = aux + v[i];
  35.             length[i] = length[i-1] + 1;
  36.         }
  37.  
  38.         if( aux > MAX )
  39.         {
  40.             MAX = aux;
  41.             END = i;
  42.         }
  43.     }
  44.  
  45.     cout << "\nSum: " << MAX << "\nStarts at: " << END-length[END]+1 << " Ends at: " << END ;
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement