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++ code to check reengagements can be done so elements sum is at most x
Suppose we have two arrays A and B of size n, and another number x. We have to check whether we can rearrange the elements in B, so that A[i] + B[1] <= x, for all i in range 0 to n-1.
So, if the input is like A = [1, 2, 3]; B = [1, 1, 2]; x = 4, then the output will be True, because if we rearrange B like [1, 2, 1], the sum values will be 1 + 1 <= 4, 2 + 2 <= 4, and 3 + 1 <= 4.
Steps
To solve this, we will follow these steps −
n := size of A ans := 1 sum := 0 for initialize i := 0, when i < n, update (increase i by 1), do: sum := A[i] + B[n - i - 1] if sum > x, then: ans := 0 if ans is non-zero, then: return true Otherwise return false
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
bool solve(vector<int> A, vector<int> B, int x){
int n = A.size();
int ans = 1;
int sum = 0;
for (int i = 0; i < n; ++i){
sum = A[i] + B[n - i - 1];
if (sum > x)
ans = 0;
}
if (ans)
return true;
else
return false;
}
int main(){
vector<int> A = { 1, 2, 3 };
vector<int> B = { 1, 1, 2 };
int x = 4;
cout << solve(A, B, x) << endl;
}
Input
{ 1, 2, 3 }, { 1, 1, 2 }, 4
Output
1
Advertisements