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

📅  最后修改于: 2021-09-07 02:09:17             🧑  作者: 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


Javascript


输出:
26

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live