Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define ll long long
- /* Approach is mentioned below code.
- */
- void solve(){ // testcases
- int n;
- scanf("%d",&n);
- int arr[n];
- for(int i=0;i<n;i++) scanf("%d",&arr[i]);
- if(n==1 || n==2){
- printf("0\n"); return;
- }
- bool brr[n];
- for(int i=0;i<n;i++) brr[i]=false;
- int prev=-1,curr=-1,next=-1;
- int cnt=0;
- for(int i=1;i<n-1;i++){
- curr=arr[i]; prev=arr[i-1]; next=arr[i+1];
- if((curr<prev && curr<next) || (curr>prev && curr>next)) brr[i]=true, cnt++;
- }
- int c=0,mc=0;
- for(int i=1;i<n-1;i++){
- if(brr[i]) c++, mc=max(mc,c);
- else c=0;
- }
- if(mc>=3) printf("%d\n",cnt-3);
- else printf("%d\n",cnt-mc);
- return;
- }
- int main(){
- int testcase=1,z=1;
- scanf("%d",&testcase);
- while(z<=testcase){
- solve(); z++;
- }
- return 0;
- }
- /*
- Approach:
- THought: as we know that by changing any one of the values in the array (arr) , we can at maximum reduce
- the intimidation by 3 (only when there are >=3 consecutive hills/valleys). (just a greedy approach )
- So, if there are >=3 consecutive hills/valleys, then ans is total hills+valleys -3;
- else{ (there are no consecutive 3 hills/valleys)
- reduce the ans by max number of consecutive hills/valleys (i.e. 0,1, or 2)
- }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement