Home >Backend Development >C++ >C++ program: Calculate the number of operations required to place an element with an index less than a value
Suppose we have an array A containing n elements. We can perform these operations multiple times -
Select any positive integer k
Select any position and insert k
# at that positionmaxj := 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 maxjExampleLet us have a look at the following implementation for better Understand −
#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 }
3
The above is the detailed content of C++ program: Calculate the number of operations required to place an element with an index less than a value. For more information, please follow other related articles on the PHP Chinese website!