C++程式中兩個陣列乘積的最大和
在這個問題中,我們得到了兩個大小為n的陣列arr1[]和arr2[]。我們的任務是建立一個程式來找到兩個陣列乘積的最大和。
問題描述 − 我們需要找到兩個陣列乘積的最大和。我們需要找到從arr1中一個元素和從arr2中其他元素相乘的最大和。
讓我們舉個例子來理解這個問題:
輸入
arr1[] = {3, 5, 6} arr2[] = {1, 4, 2}輸出
37
解釋
Maximum sum of products: 6*4 + 5*2 + 3*1 = 24 + 10 + 3 = 37
解決方案
一個簡單的解決方案是找到arr1和arr2中所有元素對。然後返回最大和。
一個高效的解決方案是將兩個陣列中最大的值相乘。一個簡單的方法是將陣列按降序排序。然後將兩個陣列中從索引0到n的所有元素相乘,並返回它們的和。
示例
程式說明了我們解決方案的工作原理:
#include<bits/stdc++.h>
using namespace std;
int calcMaxSumOfProd(int arr1[], int arr2[], int n){
int maxSum = 0;
sort(arr1, arr1 + n, greater<int>());
sort(arr2, arr2 + n, greater<int>());
for (int i = 0; i < n; i++)
maxSum += (arr1[i] * arr2[i]);
return maxSum;
}
int main() {
int arr1[] = { 3, 5, 6 };
int arr2[] = { 1, 4, 2 };
int n = sizeof(arr1)/sizeof(arr1[0]);
cout<<"The maximum Sum of Products of two arrays is "<<calcMaxSumOfProd(arr1, arr2, n);
return 0;
}輸出
The maximum Sum of Products of two arrays is 37
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP