Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <cstdlib>
- #define DECREASING -1
- #define INCREASING 1
- #define CONSTANT 0
- // Since each element is within the range [-1000000, 1000000], there could be problems with
- // functions like factorial and combination
- // calculates factorial of a number (n!)
- double factorial(int num)
- {
- double sum = 1;
- for(int i = 2 ; i <= num ; i++)
- {
- sum *= i;
- }
- return sum;
- }
- // calculates number of combinations (2,n)
- int combination(int n)
- {
- return ( factorial(n) ) / ( factorial(2) * factorial(n-2) );
- }
- // Finds number of monotonic segments, then uses combinations to count every segments combination
- int solution(std::vector<int> &A)
- {
- int segment_cnt = 0;
- int segment_length = 2;
- int prev_state;
- int current_state;
- int state_finder;
- // find first state
- state_finder = A[1] - A[0];
- // Could use switch-case (for maybe a little more efficiency)
- // or get prev_state directly with
- // state_finder = (A[1] - A[0])/ abs(A[1] - A[0])
- // but CONSTANT will cause a 0/0 division
- if(state_finder > 0)
- {
- prev_state = INCREASING;
- }
- if(state_finder == 0)
- {
- prev_state = CONSTANT;
- }
- if(state_finder < 0)
- {
- prev_state = DECREASING;
- }
- // find different monotonic segment
- for(int i = 2 ; i < A.size() ; i++)
- {
- state_finder = A[i] - A[i-1];
- if(state_finder > 0)
- {
- current_state = INCREASING;
- }
- if(state_finder == 0)
- {
- current_state = CONSTANT;
- }
- if(state_finder < 0)
- {
- current_state = DECREASING;
- }
- // if state changes, then we have a new segment
- if(current_state != prev_state)
- {
- segment_cnt += combination(segment_length);
- prev_state = current_state;
- segment_length = 2;
- continue;
- }
- segment_length++;
- }
- // add the very last segment's count
- segment_cnt += combination(segment_length);
- return segment_cnt;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement