使用C++查詢矩陣中最大和的數對
在本文中,我們將討論在給定矩陣或二維陣列中查詢具有最大和的數對。例如
Input : matrix[m][n] = { { 3, 5, 2 }, { 2, 6, 47 }, { 1, 64, 66 } } Output : 130 Explanation : maximum sum is 130 from element pair 64 and 66. Input : matrix[m][n] = { { 55, 22, 46 }, { 6, 2, 1 }, { 3, 24, 52 } } Output : 107 Explanation : maximum sum is 130 from element pair 55 and 52.
解決方法
讓我們簡要解釋一下解決給定問題而不出現任何問題的不同步驟。
暴力法
可以使用暴力法,即用前兩個元素的和初始化MAX變數,然後遍歷陣列並檢查每一對的和是否大於MAX,如果是,則將MAX更新為新的和值。但是,此過程的時間複雜度為O((m*n)2),會花費更多時間。
高效方法
可以使用一種高效的方法,即用0初始化兩個變數MAX1和MAX2,然後遍歷二維陣列;檢查當前元素是否大於MAX1。如果是,則將MAX1的值賦給MAX2,並將當前元素的值賦給MAX1。透過這種方式,我們將能夠找到兩個最大數字,顯然,這兩個最大數字的和將是最大值。
示例
#include <bits/stdc++.h> using namespace std; int main() { int m = 3, n = 3; // initialising matrix with values int matrix[m][n] = { { 55, 22, 46 }, { 6, 2, 1 }, { 3, 24, 52 } }; // initialising MAX1 and MAX2 to keep two maximum numbers. int MAX1 = INT_MIN; int MAX2 = INT_MIN; int result; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // check if the element is greater than MAX1. if (matrix[i][j] > MAX1) { MAX2 = MAX1; MAX1 = matrix[i][j]; } // check if the current element is between MAX1 and MAX2. else if (matrix[i][j] > MAX2 && matrix[i][j] <= MAX1) { MAX2 = matrix[i][j]; } } } // calculating maximum sum by adding both maximum numbers. result = MAX1 + MAX2; cout << "maximum sum in Matrix : " << result ; return 0; }
輸出
maximum sum in Matrix : 107
以上程式碼的解釋
- 將元素儲存在二維陣列中,並將MAX1和MAX2初始化為INT的最小值。
- 遍歷矩陣。
- 如果當前元素大於MAX1,則將MAX1的值賦給MAX2,並將當前元素的值賦給MAX1。
- 如果當前元素小於MAX1但大於MAX2,則將當前元素的值賦給MAX2。
- 透過將MAX1和MAX2相加來計算結果並列印結果。
結論
在本文中,我們討論了在給定矩陣中查詢具有最大和的數對。我們討論了尋找解決方案的方法,以及C++程式碼。我們可以使用其他語言(如Java、C、Python等)編寫此程式碼。希望本文對您有所幫助。
廣告