可以使用C++代码检查重新参与,以确保元素总和最多为x。
假设我们有两个大小为n的数组A和B,以及另一个数字x。我们必须检查是否可以重新排列B中的元素,以便对于所有i(范围为0到n-1),A[i] + B[i] <= x。
因此,如果输入类似于A = [1, 2, 3];B = [1, 1, 2];x = 4,则输出将为True,因为如果我们将B重新排列为[1, 2, 1],则和值将为1 + 1 <= 4,2 + 2 <= 4,以及3 + 1 <= 4。
步骤
为了解决这个问题,我们将遵循以下步骤:
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
示例
让我们看看下面的实现,以便更好地理解:
#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;
}输入
{ 1, 2, 3 }, { 1, 1, 2 }, 4输出
1
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP