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.