Given an array **arr[] **consisting of N elements, the task is to check if the given array can be sorted by picking only corner elements i.e., elements either from left or right side of the array can be chosen.
Examples:
_Input: _arr[] = {2, 3, 4, 10, 4, 3, 1}
_Output: _Yes
Explanation:
The order of picking elements from the array and placing in the sorted array are as follows:
{2, 3, 4, 10, 4, 3, 1} -> {1}
{2, 3, 4, 10, 4, 3} -> {1, 2}
{3, 4, 10, 4, 3} -> {1, 2, 3}
{4, 10, 4, 3} -> {1, 2, 3, 3}
{4, 10, 4} -> {1, 2, 3, 3, 4}
{10, 4} -> {1, 2, 3, 3, 4, 4}
{10} -> {1, 2, 3, 3, 4, 4, 10}
Input:_ a[] = {2, 4, 2, 3}_
_Output: _No
**Approach: **To solve the problem, we need to use a concept similar to Bitonic Sequence.Follow the below steps to solve the problem:
Below is implementation of above approach:
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
// Function to check if an array can
// be sorted using given operations
**bool**
check(``**int**
arr[],
**int**
n)
{
**int**
i, g;
g = 0;
**for**
(i = 1; i < n; i++) {
// If sequence becomes increasing
// after an already non-decreasing to
// non-increasing pattern
**if**
(arr[i] - arr[i - 1] > 0 && g == 1)
**return**
**false**``;
// If a decreasing pattern is observed
**if**
(arr[i] - arr[i - 1] < 0)
g = 1;
}
**return**
**true**``;
}
// Driver Code
**int**
main()
{
**int**
arr[] = { 2, 3, 4, 10, 4, 3, 1 };
**int**
n =
**sizeof**``(arr) /
**sizeof**``(``**int**``);
**if**
(check(arr, n) ==
**true**``)
cout <<
"Yes"
"\n"``;
**else**
cout <<
"No"
<<
"\n"``;
**return**
0;
}
Output:
Yes
_Time Complexity: _O(N)
Auxiliary Space:_ O(1)_
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#arrays #greedy #mathematical #pattern searching #searching #sorting #bitonic