1 year ago

#370204

test-img

Rajesh Chaudhary

Find minimum non negative integer to subtract from each element of an given array such that the array will become sorted

I need to find the minimum non-negative integer 'x' such that after subtracting 'x' from each element of the given array and taking the absolute value, the array will be sorted in non-decreasing order. If there doesn't exist any 'x' print -1.

For example, given array: [5, 3, 2, 6, 0], the answer is: 4

As,

|5-4| = 1,
|3-4| = 1,
|2-4| = 2,
|6-4| = 2,
|0-4| = 4

Array will become: [1, 1, 2, 2, 4] which is sorted

What I thought, first we check if the given array is sorted, if yes answer will be 0, else we take the average value of first two element and ceil it.

Then we subtract that average value from each element of the array and take the absolute value. If array become sorted, answer will be that average value else answer will be -1.

However, for this case [5, 7, 2, 2, 0] my answer is coming 6, but correct answer is 5.

My code:

#include<bits/stdc++.h>
using namespace std;
int n;
void solve(){
    if(n==1){
        cout<<0;
        return;
    }
    vector<int>v(n);
    int b[n];
    int i=0;
    for(auto &it:v)cin>>it,b[i++]=it;
    if(is_sorted(b,b+n)){
        cout<<0;
        return;
    }
    int k=(abs(v[0]+v[1])+1)/2;
    int a[n];
    for(int i=0;i<n;i++){
        a[i]=abs(v[i]-k);
    }
    if(is_sorted(a,a+n)){
        cout<<k;
    }
    else cout<<-1;
}
int main(){
    cin>>n;
    solve();
}

c++

arrays

sorting

greedy

0 Answers

Your Answer

Accepted video resources