Check if array can be converted into strictly decreasing sequence
Given an array arr[], the task is to check whether given array can be converted into a strictly decreasing sequence with the help of the below operation:
- Decrease any element(if it is greater than 1) by 1 in one operation
Examples:
Input: arr[] = {11, 11, 11, 11}
Output : Yes
Explanation:
The given sequence can be converted into
arr[] = {11, 10, 9, 8}
Input: arr[] = {1, 1}
Output: No
Explanation:
The given sequence cannot be converted into strictly decreasing sequence
Approach: The idea is to check whether every element of the array is greater than or equal to (N – index of element), because if it is greater than or equal to (N – index of element) that means array can be converted into [N, N-1, N-2, ….1]
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool check( int * arr, int n)
{
bool flag = true ;
for ( int i = 0; i < n; i++) {
if (arr[i] < n - i) {
flag = false ;
}
}
if (flag) {
return true ;
}
else {
return false ;
}
}
int main()
{
int arr1[] = { 11, 11, 11, 11 };
int n1 = sizeof (arr1) / sizeof (arr1[0]);
if (check(arr1, n1)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
|
Java
class GFG{
static boolean check( int []arr, int n)
{
boolean flag = true ;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] < n - i)
{
flag = false ;
}
}
if (flag)
{
return true ;
}
else
{
return false ;
}
}
public static void main(String[] args)
{
int arr1[] = { 11 , 11 , 11 , 11 };
int n1 = arr1.length;
if (check(arr1, n1))
{
System.out.print( "Yes" + "\n" );
}
else
{
System.out.print( "No" + "\n" );
}
}
}
|
Python3
def check(arr, n):
flag = True ;
for i in range (n):
if (arr[i] < n - i):
flag = False ;
if (flag):
return True ;
else :
return False ;
if __name__ = = '__main__' :
arr1 = [ 11 , 11 , 11 , 11 ];
n1 = len (arr1);
if (check(arr1, n1)):
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG{
static bool check( int []arr, int n)
{
bool flag = true ;
for ( int i = 0; i < n; i++)
{
if (arr[i] < n - i)
{
flag = false ;
}
}
if (flag)
{
return true ;
}
else
{
return false ;
}
}
static public void Main(String[] args)
{
int []arr1 = { 11, 11, 11, 11 };
int n1 = arr1.Length;
if (check(arr1, n1))
{
Console.Write( "Yes" + "\n" );
}
else
{
Console.Write( "No" + "\n" );
}
}
}
|
Javascript
<script>
function check(arr,n)
{
var flag = true ;
for (let i = 0; i < n; i++) {
if (arr[i] < n - i) {
flag = false ;
}
}
if (flag) {
return true ;
}
else {
return false ;
}
}
let arr1= [ 11, 11, 11, 11 ];
let n1 = arr1.length;
if (check(arr1, n1)) {
document.write( "Yes" );
}
else {
document.write( "No" );
}
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
29 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...