# C++ program to count number of problems can be solved from left or right end of list

C++Server Side ProgrammingProgramming

Suppose we have an array A with n elements and another number k is there. Consider there are n problems on a contest. Amal's problem solving skill is k. Amal always solves problem from any of the ends of a list. And He cannot solve problem whose difficulty is greater than k. He stops when the left and right problems' difficulty is greater than k. We have to count how many problems he can solve. A[i] represents the difficulty of ith problem.

So, if the input is like A = [4, 2, 3, 1, 5, 1, 6, 4]; k = 4, then the output will be 5, because initially solve left most problem with 4, then right most problem with 4, then cannot solve right most problem anymore, then from left, solve problems with difficulty 2, 3 and 1. In total 5 problems can be solved.

## Steps

To solve this, we will follow these steps −

n := size of A
l := 0
r := n - 1
for initialize i := 0, when i < n, update (increase i by 1), do:
if A[i] <= k and l is same as i, then:
(increase l by 1)
while A[r] <= k, do:
(decrease r by 1)
if l is same as n, then:
return n
Otherwise
return n - 1 - r + l

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(vector<int> A, int k) {
int n = A.size();
int l = 0, r = n - 1;
for (int i = 0; i < n; ++i) {
if (A[i] <= k && l == i)
++l;
}
while (A[r] <= k)
--r;
if (l == n)
return n;
else
return n - 1 - r + l;
}
int main() {
vector<int> A = { 4, 2, 3, 1, 5, 1, 6, 4 };
int k = 4;
cout << solve(A, k) << endl;
}

## Input

{ 4, 2, 3, 1, 5, 1, 6, 4 }, 4

## Output

5
Updated on 03-Mar-2022 10:43:31