C語言中矩陣兩行元素和的最大差值


給定一個矩陣,任務是找到矩陣兩行元素和之間的最大差值。假設我們有一個矩陣 M[i,j],其中 i 行 j 列。令行從 R0 到 Ri-1。差值將透過計算 (Ry 的元素之和) - (Rx 的元素之和) 來計算,其中 x<y。

現在讓我們用一個例子來理解我們必須做什麼 -

輸入 

M[4][4] = {
   { 1,2,0,5 },
   {0,1,1,0},
   {7,2,3,2}
   {1,2,4,1}};

輸出 

Maximum difference here is : 12

解釋 - 這裡第 2 行的元素和最大,為 14,第 1 行的元素和最小,為 2。所以最大差值為 14-2=12。

輸入 

M[4][4] = {
   { 0,2,0,5 },
   {0,1,4,0},
   {1,2,3,2}
   {2,2,6,0}};

輸出 

Maximum difference here is : 5

解釋 - 這裡第 4 行的元素和最大,為 10,第 2 行的元素和最小,為 5。所以最大差值為 10-5=10

下面程式中使用的解決方法如下

  • 輸入矩陣的行數和列數,確保至少有兩行。

  • 在 rowmaxd() 函式中,我們傳遞輸入矩陣及其行數和列數,並返回行和的最大差值。

  • 在這裡,我們首先將矩陣 M[row][col] 每行的元素和儲存在一個名為 RSum[i] 的陣列中。請注意,RSum[row] 的長度根據 M[row][col] 中的行數確定。

  • 然後,我們將 MD 設為 RSum[1]-RSum[0] 的最大差值。這裡 RSum[0] 是第 0 行所有元素的和,RSums[1] 是第 1 行所有元素的和。

  • 我們還假設 RSum[0] 是 RSum[row] 中最小的,並將其儲存在 MIN 變數中。

  • 在從 0 到 i 的 for 迴圈中,我們將遍歷每個 RSum[row] 並比較 RSum[i]-MIN>MD。如果是這樣,更新 MD。否則,檢查 RSum[row]<MIN 並單獨更新 MIN。

示例

#include<stdio.h>
#define MAX 100
//create function to calculate maximum difference between sum of elements of two rows such
that second row appears before the first
int rowmaxd(int M[][MAX], int row, int col){
   //for storing sum of elements of each row
   int RSum[row];
   for(int i=0;i<row;i++){
      int sum=0;
      for(int j=0;j<col;j++)
         sum+=M[i][j];
      RSum[i]=sum;
   }
   //calculate now max difference between two elements of RSum such that in RSum[j]-RSum[i], i<j
   int MD=RSum[1]-RSum[0];
   int MIN=RSum[0];
   for (i = 1; i < row; i++){
      //if this difference is more than MD,the update MD
      if(RSum[i]-MIN>MD)
         MD=RSum[i]-MIN;
      //if this value is even less than MIN,then update MIN
      if(RSum[i]<MIN)
         MIN=RSum[i];
   }
   return MD;
}
// Driver program
int main(){
   int r = 5, c = 4;
   int mat[][MAX] = {
      {-1, 2, 3, 4},
      {6, 3, 0, 1},
      {-1, 7, 8, -3},
      {3, 5, 1, 4},
      {2, 1, 1, 0}};
   cout<<”Maximum difference of sum of elements in two rows in a matrix is: ”<<rowmaxd(mat, r, c);
   return 0;
}

輸出

如果我們執行以上程式碼,我們將得到以下輸出 -

Maximum difference of sum of elements in two rows in a matrix: 5

更新於: 2020-08-14

211 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.