- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# C++ Program to count number of operations needed to place elements whose index is smaller than value

Suppose we have an array A with n elements. We can perform these operations any number of times −

Select any positive integer k

Select any position in the sequence and insert k into that position

So, the sequence is changed, we proceed with this sequence in the next operation.

We have to find minimum number of operations needed to satisfy the condition: A[i] <= i for all i in range 0 to n-1.

So, if the input is like A = [1, 2, 5, 7, 4], then the output will be 3, because we can perform the operations like: [1,2,5,7,4] to [1,2,3,5,7,4] to [1,2,3,4,5,7,4] to [1,2,3,4,5,3,7,4].

## Steps

To solve this, we will follow these steps −

maxj := 0 n := size of A for initialize i := 0, when i < n, update (increase i by 1), do: maxj := maximum of maxj and (A[i] - i - 1) return maxj

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; int solve(vector<int> A) { int maxj = 0; int n = A.size(); for (int i = 0; i < n; i++) { maxj = max(maxj, A[i] - i - 1); } return maxj; } int main() { vector<int> A = { 1, 2, 5, 7, 4 }; cout << solve(A) << endl; }

## Input

{ 1, 2, 5, 7, 4 }

## Output

3

- Related Questions & Answers
- C++ program to count minimum number of operations needed to make number n to 1
- C++ program to count expected number of operations needed for all node removal
- C++ program to count number of operations needed to reach n by paying coins
- Count smaller values whose XOR with x is greater than x in C++
- Picking all elements whose value is equal to index in JavaScript
- Program to count number of operations needed to make string as concatenation of same string twice in Python
- 8085 program to count number of elements which are less than 0A
- Program to find number of operations needed to decrease n to 0 in C++
- Program to count number of paths whose sum is k in python
- Program to count maximum number of distinct pairs whose differences are larger than target in Python
- Count smaller numbers whose XOR with n produces greater value in C++
- C++ program to count at least how many operations needed for given conditions
- Program to count number of fraction pairs whose sum is 1 in python
- Program to count number of consecutive lists whose sum is n in C++
- C++ program to find minimum how many operations needed to make number 0

Advertisements