Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements