Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. int Solution::candy(vector<int> &A) {
  2.     int n = A.size();
  3.     int ans = 1;
  4.     if(!n) return 0;
  5.     vector<int> inc(n); inc[0] = 0;
  6.     vector<int> curr(n); curr[0] = 1;
  7.     for(int i = 1; i < n; i++){
  8.         if(A[i] >= A[i-1]) inc[i] = 0;
  9.         else inc[i] = inc[i - 1] + 1;
  10.     }
  11.     for(int i = 1; i < n; i++){
  12.         int last = curr[i - 1];
  13.         if(A[i] > A[i - 1]){
  14.             curr[i] = last + 1;
  15.             ans += curr[i];
  16.         } else{
  17.             ans++;
  18.             if(last == 1){
  19.                 // Adding 1 to each one behind me
  20.                 // Example :    4 3 2 1 1 <- me
  21.                 // Since the last one is 1 and me is also 1, I need to add one to it
  22.                 // becomes 2, but the last of the last could be 2 and so on
  23.                 // so inc[i] will store how many in incresing order from right to left
  24.                 // I have so then I will increment all of them in O(1)
  25.                 ans += inc[i];  
  26.                
  27.                 // This is a tricky if for a special case
  28.                 // Exmaple :  1 2 3 4 5 6 3 2 1 1 <- me
  29.                 // With inc[i] I would add 1 to all my last 4 numbers, since I had
  30.                 // 6 3 2 1 1 to become 7 4 3 2 1 <- me, but I didnt had to inc
  31.                 // 6 to become 7 because 3 + 1 < 6, so I check if my last element of that
  32.                 // sequence is greater than the value that it should be, to uncount that
  33.                 if(curr[i - inc[i]] > inc[i]) ans--;
  34.             }
  35.             curr[i] = 1;
  36.         }
  37.     }
  38.     return ans;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement