📌  相关文章
📜  通过将成对的相邻元素与-1重复乘以最大化矩阵和

📅  最后修改于: 2021-04-17 17:00:50             🧑  作者: Mango

给定尺寸为M×N的矩阵A [] [] ,任务是通过重复选择两个相邻的矩阵元素并将它们的两个值都乘以-1来从矩阵中找到最大和

例子:

方法:要使给定矩阵的总和最大化,请执行给定操作,以使行或列中的最小元素为负(如果不可能使所有行和列元素均为正)。请按照以下步骤使总和最大化:  

  • 设具有负值的像元数为x如果x为0,即没有负值,则矩阵的总和已经是最大可能的。
  • 否则,从矩阵中获取任何负值,然后对该元素及其任何相邻单元格执行给定的操作。这导致所选元素变为正数。
  • 现在,如果所选相邻元素的值为负,则它将变为正,反之亦然。这样,每转两个负值都可以设为正。现在出现以下两种情况:
    • 如果x为偶数:在这种情况下,在x / 2圈之后,所有负值都可以设为正。因此,最大可能和等于所有像元的绝对值之和。
    • 如果x为奇数:在这种情况下,以上述方式执行操作后将剩下一个负值。现在,为了使总和最大化,需要最小化被减去或具有负号的值。为此,将负号移动到具有最小绝对值的单元格,例如minVal 。因此,最大可能的总和是所有单元格的绝对值之和– 2 * minVal

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to calculate maximum sum
// possible of a matrix by multiplying
// pairs of adjacent elements with -1
// any number of times (possibly zero)
void getMaxSum(vector > A,
               int M, int N)
{
    // Store the maximum sum
    // of matrix possible
    int sum = 0;
 
    // Stores the count of
    // negative values in the matrix
    int negative = 0;
 
    // Store minimum absolute
    // value present in the matrix
    int minVal = INT_MAX;
 
    // Traverse the matrix row-wise
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++) {
 
            // Update sum
            sum += abs(A[i][j]);
 
            // If current element is negative,
            // increment the negative count
            if (A[i][j] < 0) {
                negative++;
            }
 
            // If current value is less than
            // the overall minimum in A[],
            // update the overall minimum
            minVal = min(minVal, abs(A[i][j]));
        }
    }
 
    // If there are odd number of negative
    // values, then the answer will be
    // sum of the absolute values of
    // all elements - 2* minVal
    if (negative % 2) {
        sum -= 2 * minVal;
    }
 
    // Print maximum sum
    cout << sum;
}
 
// Driver Code
int main()
{
    // Given matrix
    vector > A = {
        { 4, -8, 6 },
        { 3, 7, 2 }
    };
 
    // Dimensions of matrix
    int M = A.size();
    int N = A[0].size();
 
    getMaxSum(A, M, N);
 
    return 0;
}


Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG
{
  static void getMaxSum(int[][] A, int M, int N)
  {
 
    // Store the maximum sum
    // of matrix possible
    int sum = 0;
 
    // Stores the count of
    // negative values in the matrix
    int negative = 0;
 
    // Store minimum absolute
    // value present in the matrix
    int minVal = Integer.MAX_VALUE;
 
    // Traverse the matrix row-wise
    for (int i = 0; i < M; i++) {
      for (int j = 0; j < N; j++) {
 
        // Update sum
        sum += Math.abs(A[i][j]);
 
        // If current element is negative,
        // increment the negative count
        if (A[i][j] < 0) {
          negative++;
        }
 
        // If current value is less than
        // the overall minimum in A[],
        // update the overall minimum
        minVal
          = Math.min(minVal, Math.abs(A[i][j]));
      }
    }
 
    // If there are odd number of negative
    // values, then the answer will be
    // sum of the absolute values of
    // all elements - 2* minVal
    if (negative % 2 != 0) {
      sum -= 2 * minVal;
    }
 
    // Print maximum sum
    System.out.println(sum);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    // Given matrix
    int[][] A = { { 4, -8, 6 }, { 3, 7, 2 } };
 
    // Dimensions of matrix
    int M = A.length;
    int N = A[0].length;
 
    getMaxSum(A, M, N);
  }
}
 
// This code is contributed by aditya7409.


Python3
# Python3 program to implement
# the above approach
import sys
 
# Function to calculate maximum sum
# possible of a matrix by multiplying
# pairs of adjacent elements with -1
# any number of times (possibly zero)
def getMaxSum(A, M, N):
   
    # Store the maximum sum
    # of matrix possible
    sum = 0
 
    # Stores the count of
    # negative values in the matrix
    negative = 0
 
    # Store minimum absolute
    # value present in the matrix
    minVal = sys.maxsize
 
    # Traverse the matrix row-wise
    for i in range(M):
        for j in range(N):
            # Update sum
            sum += abs(A[i][j])
 
            # If current element is negative,
            # increment the negative count
            if (A[i][j] < 0):
                negative +=1
 
            # If current value is less than
            # the overall minimum in A[],
            # update the overall minimum
            minVal = min(minVal, abs(A[i][j]))
 
    # If there are odd number of negative
    # values, then the answer will be
    # sum of the absolute values of
    # all elements - 2* minVal
    if (negative % 2):
        sum -= 2 * minVal
 
    # Print maximum sum
    print(sum)
 
# Driver Code
if __name__ == '__main__':
   
    # Given matrix
    A = [[4, -8, 6], [3, 7, 2]]
 
    # Dimensions of matrix
    M = len(A)
    N = len(A[0])
    getMaxSum(A, M, N)
     
    # This code is contributed by ipg2016107.


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to calculate maximum sum
// possible of a matrix by multiplying
// pairs of adjacent elements with -1
// any number of times (possibly zero)
static void getMaxSum(int[,] A, int M, int N)
{
     
    // Store the maximum sum
    // of matrix possible
    int sum = 0;
 
    // Stores the count of
    // negative values in the matrix
    int negative = 0;
 
    // Store minimum absolute
    // value present in the matrix
    int minVal = Int32.MaxValue;
 
    // Traverse the matrix row-wise
    for(int i = 0; i < M; i++)
    {
        for(int j = 0; j < N; j++)
        {
             
            // Update sum
            sum += Math.Abs(A[i, j]);
 
            // If current element is negative,
            // increment the negative count
            if (A[i, j] < 0)
            {
                negative++;
            }
 
            // If current value is less than
            // the overall minimum in A[],
            // update the overall minimum
            minVal = Math.Min(minVal,
                              Math.Abs(A[i, j]));
        }
    }
 
    // If there are odd number of negative
    // values, then the answer will be
    // sum of the absolute values of
    // all elements - 2* minVal
    if (negative % 2 != 0)
    {
        sum -= 2 * minVal;
    }
 
    // Print maximum sum
    Console.Write(sum);
}
 
// Driver Code
public static void Main()
{
     
    // Given matrix
    int[, ] A = { { 4, -8, 6 },
                  { 3, 7, 2 } };
 
    // Dimensions of matrix
    int M = A.GetLength(0);
    int N = A.GetLength(1);
 
    getMaxSum(A, M, N);
}
}
 
// This code is contributed by chitranayal


输出:
26

时间复杂度: O(M * N)
辅助空间: O(1)