Advertisement
siddharth963

cf B #695 doubt

Jan 9th, 2021 (edited)
393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. /* Approach is mentioned below code.
  5. */
  6. void solve(){ // testcases
  7.     int n;
  8.     scanf("%d",&n);
  9.     int arr[n];
  10.     for(int i=0;i<n;i++) scanf("%d",&arr[i]);
  11.     if(n==1 || n==2){
  12.         printf("0\n"); return;
  13.     }
  14.  
  15.     bool brr[n];
  16.     for(int i=0;i<n;i++) brr[i]=false;
  17.     int prev=-1,curr=-1,next=-1;
  18.     int cnt=0;
  19.     for(int i=1;i<n-1;i++){
  20.         curr=arr[i]; prev=arr[i-1]; next=arr[i+1];
  21.         if((curr<prev && curr<next) || (curr>prev && curr>next)) brr[i]=true, cnt++;
  22.     }
  23.     int c=0,mc=0;
  24.     for(int i=1;i<n-1;i++){
  25.         if(brr[i]) c++, mc=max(mc,c);
  26.         else c=0;
  27.     }
  28.     if(mc>=3) printf("%d\n",cnt-3);
  29.     else printf("%d\n",cnt-mc);
  30.     return;
  31. }
  32.  
  33. int main(){
  34.     int testcase=1,z=1;
  35.     scanf("%d",&testcase);
  36.     while(z<=testcase){
  37.         solve(); z++;
  38.     }
  39.     return 0;
  40. }
  41. /*
  42.  
  43. Approach:
  44.  
  45. THought: as we know that by changing any one of the values in the array (arr) , we can at maximum reduce
  46. the intimidation by 3 (only when there are >=3 consecutive hills/valleys). (just a greedy approach )
  47.  
  48. So, if there are >=3 consecutive hills/valleys, then ans is total hills+valleys -3;
  49. else{ (there are no consecutive 3 hills/valleys)
  50.     reduce the ans by max number of consecutive hills/valleys  (i.e. 0,1, or 2)
  51. }
  52.  
  53.  
  54. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement