📌  相关文章
📜  通过执行给定的操作从给定的矩阵可能的最大和

📅  最后修改于: 2021-09-22 09:43:38             🧑  作者: Mango

给定维度为2 * N的矩阵arr[][] ,任务是通过从每一列中最多选择一个元素来最大化可能的总和,这样不会从同一行中选择两个连续的元素。

例子:

动态规划方法:该问题可以使用动态规划解决。请按照以下步骤解决问题:

  • 初始化数组dp[][]以存储以下转换状态:
  • (N – 2)横移0列和每行,更新DP [j]的[I]作为DP [j]的[I] = MAX(DP [(j ^ 1)] [i + 1的], dp[j][i+2]) + arr[j][i]其中^代表按位异或。
  • 完成遍历后,打印max(dp[0][0], dp[1][0])作为最大可能和。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
#include 
using namespace std;
 
// Function to print the maximum sum
void maxSum(vector > arr,
            int n, int m)
{
 
    // Dp table
    vector > dp(n);
 
    // Initializing dp array with 0s
    for (int i = 0; i < 2; i++) {
        dp[i] = vector(m);
        for (int j = 0; j < m; j++) {
            dp[i][j] = 0;
        }
    }
 
    // Base case
    dp[0][m - 1] = arr[0][m - 1];
    dp[1][m - 1] = arr[1][m - 1];
 
    // Traverse each column
    for (int j = m - 2; j >= 0; j--) {
 
        // Update answer for both rows
        for (int i = 0; i < 2; i++) {
            if (i == 1) {
                dp[i][j] = max(
                    arr[i][j] + dp[0][j + 1],
                    arr[i][j] + dp[0][j + 2]);
            }
            else {
                dp[i][j] = max(
                    arr[i][j] + dp[1][j + 1],
                    arr[i][j] + dp[1][j + 2]);
            }
        }
    }
 
    // Print the maximum sum
    cout << max(dp[0][0], dp[1][0]);
}
 
// Driver Code
int main()
{
 
    // Given array
    vector > arr
        = { { 1, 50, 21, 5 },
            { 2, 10, 10, 5 } };
 
    // Number of Columns
    int N = arr[0].size();
 
    // Function calls
    maxSum(arr, 2, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to print the maximum sum
static void maxSum(int[][] arr, int n, int m)
{
     
    // Dp table
    int[][] dp = new int[n][m + 1];
 
    // Initializing dp array with 0s
    for(int i = 0; i < 2; i++)
    {
        for(int j = 0; j <= m; j++)
        {
            dp[i][j] = 0;
        }
    }
 
    // Base case
    dp[0][m - 1] = arr[0][m - 1];
    dp[1][m - 1] = arr[1][m - 1];
 
    // Traverse each column
    for(int j = m - 2; j >= 0; j--)
    {
 
        // Update answer for both rows
        for (int i = 0; i < 2; i++)
        {
            if (i == 1)
            {
                dp[i][j] = Math.max(
                    arr[i][j] + dp[0][j + 1],
                    arr[i][j] + dp[0][j + 2]);
            }
            else
            {
                dp[i][j] = Math.max(
                    arr[i][j] + dp[1][j + 1],
                    arr[i][j] + dp[1][j + 2]);
            }
        }
    }
 
    // Print the maximum sum
    System.out.println(Math.max(dp[0][0],
                                dp[1][0]));
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array
    int[][] arr = { { 1, 50, 21, 5 },
                    { 2, 10, 10, 5 } };
 
    // Number of Columns
    int N = arr[0].length;
 
    // Function calls
    maxSum(arr, 2, N);
}
}
 
// This code is contributed by akhilsaini


Python3
# Python3 program for the above approach
 
# Function to prthe maximum sum
def maxSum(arr, n, m):
 
    # Dp table
    dp = [[0 for i in range(m + 1)]
             for i in range(2)]
 
    # Initializing dp array with 0s
    # for (i = 0 i < 2 i++) {
    #     dp[i] = vector(m)
    #     for (j = 0 j < m j++) {
    #         dp[i][j] = 0
    #     }
    # }
 
    # Base case
    dp[0][m - 1] = arr[0][m - 1]
    dp[1][m - 1] = arr[1][m - 1]
 
    # Traverse each column
    for j in range(m - 2, -1, -1):
 
        # Update answer for both rows
        for i in range(2):
            if (i == 1):
                dp[i][j] = max(arr[i][j] + dp[0][j + 1],
                               arr[i][j] + dp[0][j + 2])
            else:
                dp[i][j] = max(arr[i][j] + dp[1][j + 1],
                               arr[i][j] + dp[1][j + 2])
 
    # Print the maximum sum
    print(max(dp[0][0], dp[1][0]))
 
# Driver Code
if __name__ == '__main__':
 
    # Given array
    arr = [ [ 1, 50, 21, 5 ],
            [ 2, 10, 10, 5 ] ]
 
    # Number of Columns
    N = len(arr[0])
 
    # Function calls
    maxSum(arr, 2, N)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to print the maximum sum
static void maxSum(int[, ] arr, int n, int m)
{
     
    // Dp table
    int[, ] dp = new int[n, m + 1];
 
    // Initializing dp array with 0s
    for(int i = 0; i < 2; i++)
    {
        for(int j = 0; j <= m; j++)
        {
            dp[i, j] = 0;
        }
    }
 
    // Base case
    dp[0, m - 1] = arr[0, m - 1];
    dp[1, m - 1] = arr[1, m - 1];
 
    // Traverse each column
    for(int j = m - 2; j >= 0; j--)
    {
         
        // Update answer for both rows
        for(int i = 0; i < 2; i++)
        {
            if (i == 1)
            {
                dp[i, j] = Math.Max(
                    arr[i, j] + dp[0, j + 1],
                    arr[i, j] + dp[0, j + 2]);
            }
            else
            {
                dp[i, j] = Math.Max(
                    arr[i, j] + dp[1, j + 1],
                    arr[i, j] + dp[1, j + 2]);
            }
        }
    }
 
    // Print the maximum sum
    Console.WriteLine(Math.Max(dp[0, 0],
                               dp[1, 0]));
}
 
// Driver Code
public static void Main()
{
     
    // Given array
    int[, ] arr = { { 1, 50, 21, 5 },
                    { 2, 10, 10, 5 } };
 
    // Number of Columns
    int N = arr.GetLength(1);
     
    // Function calls
    maxSum(arr, 2, N);
}
}
 
// This code is contributed by akhilsaini


Javascript


C++
// C++ code for the above approach
#include 
using namespace std;
 
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
void maxSum(vector > arr, int n)
{
     
    // Initialize variables
    int r1 = 0, r2 = 0;
     
    // Traverse each column
    for(int i = 0; i < n; i++)
    {
         
        // r1, r2 = max(r1, r2 + arr[0][i]),
        // max(r2, r1 + arr[1][i])
        int temp = r1;
         
        r1 = max(r1, r2 + arr[0][i]);
        r2 = max(r2, temp + arr[1][i]);
    }
 
    // Print answer
    cout << max(r1, r2);
}
 
// Driver Code
int main()
{
    vector> arr = { { 1, 50, 21, 5 },
                                { 2, 10, 10, 5 } };
 
    // Numberof columns
    int n = arr[0].size();
 
    maxSum(arr, n);
 
    return 0;
}
 
// This code is contributed by akhilsaini


Java
// Java code for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
static void maxSum(int[][] arr, int n)
{
     
    // Initialize variables
    int r1 = 0, r2 = 0;
 
    // Traverse each column
    for(int i = 0; i < n; i++)
    {
        int temp = r1;
         
        r1 = Math.max(r1, r2 + arr[0][i]);
        r2 = Math.max(r2, temp + arr[1][i]);
    }
 
    // Print answer
    System.out.println(Math.max(r1, r2));
}
 
// Driver Code
public static void main(String args[])
{
    int[][] arr = { { 1, 50, 21, 5 },
                    { 2, 10, 10, 5 } };
 
    // Numberof columns
    int n = arr[0].length;
 
    maxSum(arr, n);
}
}
 
// This code is contributed by akhilsaini


Python
# Python code for the above approach
 
# Function to print the maximum sum
# possible by selecting at most one
# element from each column such that
# no consecutive pairs are selected
# from a single row
 
def maxSum(arr, n):
 
    # Initialize variables
    r1 = r2 = 0
 
    # Traverse each column
    for i in range(n):
        r1, r2 = max(r1, r2 + arr[0][i]), max(r2, r1 + arr[1][i])
 
        # Print answer
    print(max(r1, r2))
 
 
# Driver Code
 
arr = [[1, 50, 21, 5], [2, 10, 10, 5]]
 
# Numberof columns
n = len(arr[0])
 
maxSum(arr, n)


C#
// C# code for the above approach
using System;
 
class GFG{
 
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
static void maxSum(int[, ] arr, int n)
{
     
    // Initialize variables
    int r1 = 0, r2 = 0;
 
    // Traverse each column
    for(int i = 0; i < n; i++)
    {
        int temp = r1;
         
        r1 = Math.Max(r1, r2 + arr[0, i]);
        r2 = Math.Max(r2, temp + arr[1, i]);
    }
 
    // Print answer
    Console.WriteLine(Math.Max(r1, r2));
}
 
// Driver Code
public static void Main()
{
    int[, ] arr = { { 1, 50, 21, 5 },
                    { 2, 10, 10, 5 } };
 
    // Numberof columns
    int n = arr.GetLength(1);
 
    maxSum(arr, n);
}
}
 
// This code is contributed by akhilsaini


Javascript


输出:
67

时间复杂度: O(N),其中N是列数。
辅助空间: O(N)

高效方法:按照以下步骤优化上述方法

  1. 初始化两个变量r1r2存储最大总和为12的行分别。
  2. 遍历在该行的长度,即0到N – 1,对于每个元素ARR [I],更新R1r1 = MAX(R1,R2 + ARR [0] [1])r2r2 = MAX(R2 , r1 + arr[1][i])
  3. 遍历后,打印max(r1, r2)作为最大和。

下面是上述方法的实现:

C++

// C++ code for the above approach
#include 
using namespace std;
 
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
void maxSum(vector > arr, int n)
{
     
    // Initialize variables
    int r1 = 0, r2 = 0;
     
    // Traverse each column
    for(int i = 0; i < n; i++)
    {
         
        // r1, r2 = max(r1, r2 + arr[0][i]),
        // max(r2, r1 + arr[1][i])
        int temp = r1;
         
        r1 = max(r1, r2 + arr[0][i]);
        r2 = max(r2, temp + arr[1][i]);
    }
 
    // Print answer
    cout << max(r1, r2);
}
 
// Driver Code
int main()
{
    vector> arr = { { 1, 50, 21, 5 },
                                { 2, 10, 10, 5 } };
 
    // Numberof columns
    int n = arr[0].size();
 
    maxSum(arr, n);
 
    return 0;
}
 
// This code is contributed by akhilsaini

Java

// Java code for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
static void maxSum(int[][] arr, int n)
{
     
    // Initialize variables
    int r1 = 0, r2 = 0;
 
    // Traverse each column
    for(int i = 0; i < n; i++)
    {
        int temp = r1;
         
        r1 = Math.max(r1, r2 + arr[0][i]);
        r2 = Math.max(r2, temp + arr[1][i]);
    }
 
    // Print answer
    System.out.println(Math.max(r1, r2));
}
 
// Driver Code
public static void main(String args[])
{
    int[][] arr = { { 1, 50, 21, 5 },
                    { 2, 10, 10, 5 } };
 
    // Numberof columns
    int n = arr[0].length;
 
    maxSum(arr, n);
}
}
 
// This code is contributed by akhilsaini

Python

# Python code for the above approach
 
# Function to print the maximum sum
# possible by selecting at most one
# element from each column such that
# no consecutive pairs are selected
# from a single row
 
def maxSum(arr, n):
 
    # Initialize variables
    r1 = r2 = 0
 
    # Traverse each column
    for i in range(n):
        r1, r2 = max(r1, r2 + arr[0][i]), max(r2, r1 + arr[1][i])
 
        # Print answer
    print(max(r1, r2))
 
 
# Driver Code
 
arr = [[1, 50, 21, 5], [2, 10, 10, 5]]
 
# Numberof columns
n = len(arr[0])
 
maxSum(arr, n)

C#

// C# code for the above approach
using System;
 
class GFG{
 
// Function to print the maximum sum
// possible by selecting at most one
// element from each column such that
// no consecutive pairs are selected
// from a single row
static void maxSum(int[, ] arr, int n)
{
     
    // Initialize variables
    int r1 = 0, r2 = 0;
 
    // Traverse each column
    for(int i = 0; i < n; i++)
    {
        int temp = r1;
         
        r1 = Math.Max(r1, r2 + arr[0, i]);
        r2 = Math.Max(r2, temp + arr[1, i]);
    }
 
    // Print answer
    Console.WriteLine(Math.Max(r1, r2));
}
 
// Driver Code
public static void Main()
{
    int[, ] arr = { { 1, 50, 21, 5 },
                    { 2, 10, 10, 5 } };
 
    // Numberof columns
    int n = arr.GetLength(1);
 
    maxSum(arr, n);
}
}
 
// This code is contributed by akhilsaini

Javascript


输出:
67

时间复杂度: O(N),其中 N 是列数。
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程