📌  相关文章
📜  通过根据给定条件从矩阵中选择 X 个元素来实现最大和

📅  最后修改于: 2021-09-07 02:35:07             🧑  作者: Mango

给定一个维度为N × M的矩阵G[][]由正整数组成,任务是考虑到G[i][j]只能从矩阵中选择的条件,从具有最大和的矩阵中选择X 个元素除非所有的元素G [I]被选择[K],其中≤ķ<即,第j在当前第i行,可以选择其所有的电流的前述元素元素的第i行已经被选择为0J .

例子:

朴素的方法:解决这个问题的最简单的方法是计算所有可能的M 个选择的总和,并在其中找到最大的总和

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

高效方法:上述方法可以使用动态规划进行优化。主要的状态是:

  1. 选择的行数: i
  2. 选择的元素数: j

初始化矩阵dp[][]使得dp[i][j]存储通过从前i行中选择j 个元素可以获得的最大可能总和。

dp[][] 的转换如下:

下面是上述方法的实现:

C++14
// C++14 program to implement 
// the above approach 
#include 
using namespace std;
 
int n, m, X;
 
// Function to calculate the maximum
// possible sum by selecting X elements
// from the Matrix
int maxSum(vector> grid)
{
     
    // Generate prefix sum of the matrix
    vector> prefsum(n, vector(m));
 
    for(int i = 0; i < n; i++)
    {
        for(int x = 0; x < m; x++)
        {
            if (x == 0)
                prefsum[i][x] = grid[i][x];
            else
                prefsum[i][x] = prefsum[i][x - 1] +
                                   grid[i][x];
        }
    }
 
    vector> dp(n, vector(X + 1, INT_MIN));
 
    // Maximum possible sum by selecting
    // 0 elements from the first i rows
    for(int i = 0; i < n; i++)
           dp[i][0] = 0;
 
    // If a single row is present
    for(int i = 1; i <= min(m, X); ++i)
    {
        dp[0][i] = dp[0][i - 1] +
                 grid[0][i - 1];
    }
 
    for(int i = 1; i < n; ++i)
    {
        for(int j = 1; j <= X; ++j)
        {
             
            // If elements from the
            // current row is not selected
            dp[i][j] = dp[i - 1][j];
 
            // Iterate over all possible
            // selections from current row
            for(int x = 1; x <= min(j, m); x++)
            {
                dp[i][j] = max(dp[i][j],
                               dp[i - 1][j - x] +
                              prefsum[i][x - 1]);
            }
        }
    }
     
    // Return maximum possible sum
    return dp[n - 1][X];
}
 
// Driver code
int main()
{
    n = 4;
    m = 4;
    X = 6;
     
    vector> grid = { { 3, 2, 6, 1 },
                                 { 1, 9, 2, 4 },
                                 { 4, 1, 3, 9 },
                                 { 3, 8, 2, 1 } };
     
    int ans = maxSum(grid);
     
    cout << (ans);
    return 0;
}
 
// This code is contributed by mohit kumar 29


Java
// Java program to implement
// the above approach
import java.util.*;
import java.io.*;
 
class GFG {
 
    static int n, m, X;
 
    // Function to calculate the maximum
    // possible sum by selecting X elements
    // from the Matrix
    public static int maxSum(int[][] grid)
    {
 
        // Generate prefix sum of the matrix
        int prefsum[][] = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int x = 0; x < m; x++) {
                if (x == 0)
                    prefsum[i][x] = grid[i][x];
                else
                    prefsum[i][x]
                        = prefsum[i][x - 1] + grid[i][x];
            }
        }
 
        int dp[][] = new int[n][X + 1];
 
        // Initialize dp[][]
        for (int dpp[] : dp)
            Arrays.fill(dpp, Integer.MIN_VALUE);
 
        // Maximum possible sum by selecting
        // 0 elements from the first i rows
        for (int i = 0; i < n; i++)
            dp[i][0] = 0;
 
        // If a single row is present
        for (int i = 1; i <= Math.min(m, X); ++i) {
            dp[0][i] = dp[0][i - 1] + grid[0][i - 1];
        }
 
        for (int i = 1; i < n; ++i) {
            for (int j = 1; j <= X; ++j) {
 
                // If elements from the
                // current row is not selected
                dp[i][j] = dp[i - 1][j];
 
                // Iterate over all possible
                // selections from current row
                for (int x = 1; x <= Math.min(j, m);
                     x++) {
                    dp[i][j]
                        = Math.max(dp[i][j],
                                   dp[i - 1][j - x]
                                       + prefsum[i][x - 1]);
                }
            }
        }
 
        // Return maximum possible sum
        return dp[n - 1][X];
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        n = 4;
        m = 4;
        X = 6;
 
        int grid[][] = { { 3, 2, 6, 1 },
                         { 1, 9, 2, 4 },
                         { 4, 1, 3, 9 },
                         { 3, 8, 2, 1 } };
 
        int ans = maxSum(grid);
 
        System.out.println(ans);
    }
}


Python3
# Python3 program to implement
# the above approach
import sys
 
# Function to calculate the maximum
# possible sum by selecting X elements
# from the Matrix
def maxSum(grid):
     
    # Generate prefix sum of the matrix
    prefsum = [[0 for x in range(m)]
                  for y in range(m)]
                   
    for i in range(n):
        for x in range(m):
            if (x == 0):
                prefsum[i][x] = grid[i][x]
            else:
                prefsum[i][x] = (prefsum[i][x - 1] +
                                    grid[i][x])
 
    dp = [[-sys.maxsize - 1 for x in range(X + 1)]
                            for y in range(n)]
 
    # Maximum possible sum by selecting
    # 0 elements from the first i rows
    for i in range(n):
        dp[i][0] = 0
 
    # If a single row is present
    for i in range(1, min(m, X)):
        dp[0][i] = (dp[0][i - 1] +
                  grid[0][i - 1])
 
    for i in range(1, n):
        for j in range(1, X + 1):
 
            # If elements from the
            # current row is not selected
            dp[i][j] = dp[i - 1][j]
 
            # Iterate over all possible
            # selections from current row
            for x in range(1, min(j, m) + 1):
                    dp[i][j] = max(dp[i][j],
                                   dp[i - 1][j - x] +
                              prefsum[i][x - 1])
 
    # Return maximum possible sum
    return dp[n - 1][X]
 
# Driver Code
if __name__ == "__main__":
     
    n = 4
    m = 4
    X = 6
 
    grid = [ [ 3, 2, 6, 1 ],
             [ 1, 9, 2, 4 ],
             [ 4, 1, 3, 9 ],
             [ 3, 8, 2, 1 ] ]
    ans = maxSum(grid)
 
    print(ans)
 
# This code is contributed by chitranayal


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
static int n, m, X;
 
// Function to calculate the maximum
// possible sum by selecting X elements
// from the Matrix
public static int maxSum(int[,] grid)
{
     
    // Generate prefix sum of the matrix
    int [,]prefsum = new int[n, m];
     
    for(int i = 0; i < n; i++)
    {
        for(int x = 0; x < m; x++)
        {
            if (x == 0)
                prefsum[i, x] = grid[i, x];
            else
                prefsum[i, x] = prefsum[i, x - 1] +
                                   grid[i, x];
        }
    }
 
    int [,]dp = new int[n, X + 1];
 
    // Initialize [,]dp
    for(int i = 1; i < n; i++)
        for(int j = 1; j <= X; ++j)
            dp[i, j] = int.MinValue;
             
    // Maximum possible sum by selecting
    // 0 elements from the first i rows
    for(int i = 0; i < n; i++)
        dp[i, 0] = 0;
 
    // If a single row is present
    for(int i = 1; i <= Math.Min(m, X); ++i)
    {
        dp[0, i] = dp[0, i - 1] + grid[0, i - 1];
    }
 
    for(int i = 1; i < n; ++i)
    {
        for(int j = 1; j <= X; ++j)
        {
             
            // If elements from the
            // current row is not selected
            dp[i, j] = dp[i - 1, j];
 
            // Iterate over all possible
            // selections from current row
            for(int x = 1; x <= Math.Min(j, m); x++)
            {
                dp[i, j] = Math.Max(dp[i, j],
                                    dp[i - 1, j - x] +
                               prefsum[i, x - 1]);
            }
        }
    }
     
    // Return maximum possible sum
    return dp[n - 1, X];
}
 
// Driver Code
public static void Main(String[] args)
{
    n = 4;
    m = 4;
    X = 6;
 
    int [,]grid = { { 3, 2, 6, 1 },
                    { 1, 9, 2, 4 },
                    { 4, 1, 3, 9 },
                    { 3, 8, 2, 1 } };
 
    int ans = maxSum(grid);
 
    Console.WriteLine(ans);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
28

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

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