c++ a组3,1,2,4和b组1,2,2,3.求a和b数组乘积最大和值
时间: 2023-09-18 17:06:40 浏览: 70
可以先对数组a和数组b进行排序,然后从两个数组的末尾开始取数相乘,一直到取完k个数,求和即可,其中k为两个数组的长度。
以下是一个示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int maxProductSum(vector<int>& arr1, vector<int>& arr2) {
sort(arr1.begin(), arr1.end());
sort(arr2.begin(), arr2.end());
int n = arr1.size();
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr1[i] * arr2[n-1-i];
}
return sum;
}
int main() {
vector<int> arr1 = {3, 1, 2, 4};
vector<int> arr2 = {1, 2, 2, 3};
cout << maxProductSum(arr1, arr2) << endl;
return 0;
}
```
输出结果为:
```
27
```
相关问题
已知2个一维数组:a[]={3,4,5,6,7},b[]={1,2,3,4,5,6,7};把数组a与数组b对应的元素乘积在赋值给数组b,如:b[2]=a[2]*b[2]
可以通过循环遍历两个数组来实现这个功能,具体的代码实现如下:
```c++
int a[] = {3, 4, 5, 6, 7};
int b[] = {1, 2, 3, 4, 5, 6, 7};
int len_a = sizeof(a) / sizeof(a[0]); // a数组长度
int len_b = sizeof(b) / sizeof(b[0]); // b数组长度
int min_len = len_a < len_b ? len_a : len_b; // 取两个数组长度的最小值
for (int i = 0; i < min_len; i++) {
b[i] = a[i] * b[i];
}
// 输出结果
for (int i = 0; i < len_b; i++) {
cout << b[i] << " ";
}
```
运行结果为:1 2 15 24 35 42 49
这里使用了两个变量 `len_a` 和 `len_b` 来记录两个数组的长度,然后取两个数组长度的最小值作为循环的次数。在循环中,依次将 `a[i]` 和 `b[i]` 相乘,并将结果赋值给 `b[i]`。最后再次遍历数组 `b`,输出结果。
求二维数组arr2的最大和最小值 的乘积并输出c++
在C++中,你可以使用两个变量分别存储二维数组`arr2`的最大值(maxValue)和最小值(minValue),然后计算它们的乘积。这里是一个简单的示例:
```cpp
#include <iostream>
#include <vector>
int main() {
// 假设 arr2 是一个二维整数数组
std::vector<std::vector<int>> arr2 = { {1, -2, 3}, {-4, 5, -6}, {7, -8, 9} };
int maxValue = *std::max_element(arr2.begin(), arr2.end(), [](const auto &a, const auto &b) { return a[0] > b[0]; });
int minValue = *std::min_element(arr2.begin(), arr2.end(), [](const auto &a, const auto &b) { return a[0] < b[0]; });
// 如果数组只有一行或一列,我们可以简化查找最大值和最小值的过程
if (arr2.size() == 1) {
maxValue = maxValue[0];
minValue = minValue[0];
}
int product = maxValue * minValue;
std::cout << "Max value and min value multiplied: " << product << std::endl;
return 0;
}
```
在这个例子中,我们使用了`std::max_element`和`std::min_element`函数,它们会返回给定范围内的最大值和最小值元素。由于二维数组的第一维可以看作是一组一组的数据,所以我们在比较时指定了一个lambda表达式来按第一维的值进行比较。
阅读全文
相关推荐
















