dimanche 25 avril 2021

Problems with 2 and 3 member arrays in relation to a specific question

The problem is: You are given S a sequence of n integers i.e. S = s1, s2, ..., sn. Compute if it is possible to split S into two parts : s1, s2, ..., si and si+1, si+2, ….., sn (0 <= i <= n) in such a way that the first part is strictly decreasing while the second is strictly increasing one.

My solution is

#include<iostream>
using namespace std;

int main() {
        int n,arr[100],counter=1;
        cin>>n;
        for(int i=0;i<n;i++){
                cin>>arr[i];
        }
        for(int i=0;i<n-1;i++){
                if(arr[i]>arr[i+1]){
                        counter++;
                }
                else{
                        break;
                }
        }
        if(counter==n-1&&counter!=1&&counter!=2){
                cout<<"false";
                return 0;
        }
        for(;counter<n-1;counter++){
                if(arr[counter]<arr[counter+1]){
                        continue;
                }
                else{
                        cout<<"false";
                        return 0;
                }
        }
        cout<<"true";
        return 0;
}

Now i did this with hit and trial and it took me a really long time to be able to figure out how to deal with arrays with 2 or 3 members. What was giving me a tough time was this block

if(counter==n-1&&counter!=1&&counter!=2){
                cout<<"false";
                return 0;
        }

i know it isn't the most elegant solution. can somebody help me come up with a better solution for this problem?

Aucun commentaire:

Enregistrer un commentaire