Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. #include <vector>
  2. #include <cstdlib>
  3.  
  4. #define DECREASING -1
  5. #define INCREASING  1
  6. #define CONSTANT    0
  7.  
  8. // Since each element is within the range [-1000000, 1000000], there could be problems with
  9. // functions like factorial and combination
  10.  
  11. // calculates factorial of a number (n!)
  12. double factorial(int num)
  13. {
  14.     double sum = 1;
  15.    
  16.     for(int i = 2 ; i <= num ; i++)
  17.     {
  18.         sum *= i;  
  19.     }
  20.    
  21.     return sum;
  22. }
  23.  
  24. // calculates number of combinations (2,n)
  25. int combination(int n)
  26. {
  27.     return ( factorial(n) ) / ( factorial(2) * factorial(n-2) );
  28. }
  29.  
  30. // Finds number of monotonic segments, then uses combinations to count every segments combination
  31. int solution(std::vector<int> &A)
  32. {
  33.     int segment_cnt = 0;
  34.     int segment_length = 2;
  35.     int prev_state;
  36.     int current_state;
  37.     int state_finder;
  38.    
  39.     // find first state
  40.     state_finder = A[1] - A[0];
  41.    
  42.     // Could use switch-case (for maybe a little more efficiency)
  43.     // or get prev_state directly with
  44.     // state_finder = (A[1] - A[0])/ abs(A[1] - A[0])
  45.     // but CONSTANT will cause a 0/0 division
  46.     if(state_finder > 0)
  47.     {
  48.         prev_state = INCREASING;
  49.     }
  50.    
  51.     if(state_finder == 0)
  52.     {
  53.         prev_state = CONSTANT;
  54.     }
  55.    
  56.     if(state_finder < 0)
  57.     {
  58.         prev_state = DECREASING;
  59.     }
  60.    
  61.     // find different monotonic segment
  62.     for(int i = 2 ; i < A.size() ; i++)
  63.     {
  64.         state_finder = A[i] - A[i-1];
  65.         if(state_finder > 0)
  66.         {
  67.             current_state = INCREASING;
  68.         }
  69.        
  70.         if(state_finder == 0)
  71.         {
  72.             current_state = CONSTANT;
  73.         }
  74.        
  75.         if(state_finder < 0)
  76.         {
  77.             current_state = DECREASING;
  78.         }
  79.        
  80.         // if state changes, then we have a new segment
  81.         if(current_state != prev_state)
  82.         {
  83.             segment_cnt += combination(segment_length);
  84.             prev_state = current_state;
  85.             segment_length = 2;
  86.             continue;
  87.         }
  88.        
  89.         segment_length++;
  90.        
  91.     }
  92.    
  93.     // add the very last segment's count
  94.     segment_cnt += combination(segment_length);
  95.    
  96.    
  97.     return segment_cnt;  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement