📌  相关文章
📜  从矩阵中选择的 K 个元素的最大总和

📅  最后修改于: 2022-05-13 01:56:04.365000             🧑  作者: Mango

从矩阵中选择的 K 个元素的最大总和

给定一个正整数K和一个由整数组成的维度为N*M的矩阵arr[][] ,任务是从给定矩阵中找到可能的K个元素的最大总和。

例子:

朴素方法:解决问题的最简单方法是从矩阵中生成所有可能的大小为 K的子集,并从这些子集中计算可能的最大和。请按照以下步骤解决给定的问题:

  1. 在给定的矩阵mat[]中按降序对所有数组进行排序。
  2. 初始化一个矩阵, prefixSum[][] ,它存储给定矩阵的每一行的前缀和。
  3. 定义一个函数maximumSum() ,它递归地创建K个元素的所有组合并使用以下步骤返回最大和:
    • 初始化两个变量,比如id0remp ,分别代表sum中包含的元素和需要包含的元素个数。
    • 现在在每个递归调用中执行以下步骤:
      • 遍历prefixSum[id]中的每个元素并递归调用两个递归调用,包括或不包括当前值。
      • 如果它包含当前元素,则检查下面数组中的所有组合。
      • 最后,它会在取一个元素而不取它之后返回最大权重。
  4. 完成上述步骤后,打印函数maximumSum()的返回值。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum sum of K
// elements from the matrix
int maximumSum(vector >& prefixSum,
               int K, int N, int rem, int id)
{
    // Stores the maximum sum of K elements
    int ans = INT_MIN;
 
    // Base Case
    if (rem == 0)
        return 0;
 
    if (id >= N || rem < 0)
        return INT_MIN;
 
    // Iterate over K elements and find
    // the maximum sum
    for (int i = 0; i <= K; i++) {
        ans = max(ans, prefixSum[id][i]
                           + maximumSum(prefixSum, K, N,
                                        rem - i, id + 1));
    }
 
    // Return the maximum sum obtained
    return ans;
}
 
// Function to find the maximum sum of K
// element from the given matrix
void findSum(vector >& arr,
             int N, int K, int P)
{
 
    // Stores the prefix sum of the matrix
    vector > prefixSum(N,
                                   vector(K + 1, 0));
 
    // Sorting the arrays
    for (int i = 0; i < arr.size(); i++) {
        sort(arr[i].begin(), arr[i].end(),
             greater());
    }
 
    // Storing prefix sum in matrix prefixSum
    for (int i = 0; i < N; i++) {
        int sum = 0;
        for (int j = 1; j <= K; j++) {
            sum += arr[i][j - 1];
            prefixSum[i][j] = sum;
        }
    }
 
    // Print the maximum sum
    cout << maximumSum(prefixSum, K, N, P, 0);
}
 
// Driver Code
int main()
{
    vector > arr
        = { { 80, 80 }, { 15, 50 }, { 20, 10 } };
    int N = arr.size();
    int M = arr[0].size();
    int K = 3;
 
    findSum(arr, N, M, K);
 
    return 0;
}


Python3
# Python3 program for the above approach
import sys
 
# Function to find the maximum sum of K
# elements from the matrix
def maximumSum(prefixSum, K, N, rem, Id):
   
    # Stores the maximum sum of K elements
    ans = -sys.maxsize
  
    # Base Case
    if rem == 0:
        return 0
  
    if Id >= N or rem < 0:
        return -sys.maxsize
  
    # Iterate over K elements and find
    # the maximum sum
    for i in range(K + 1):
        ans = max(ans, prefixSum[Id][i] + maximumSum(prefixSum, K, N, rem - i, Id + 1))
  
    # Return the maximum sum obtained
    return ans
  
# Function to find the maximum sum of K
# element from the given matrix
def findSum(arr, N, K, P):
    # Stores the prefix sum of the matrix
    prefixSum = [[0 for i in range(K + 1)] for j in range(N)]
  
    # Sorting the arrays
    for i in range(len(arr)):
        arr[i].sort()
        arr[i].reverse()
  
    # Storing prefix sum in matrix prefixSum
    for i in range(N):
        Sum = 0
        for j in range(1, K + 1):
            Sum += arr[i][j - 1]
            prefixSum[i][j] = Sum
  
    # Print the maximum sum
    print(maximumSum(prefixSum, K, N, P, 0))
 
arr = [ [ 80, 80 ], [ 15, 50 ], [ 20, 10 ] ]
N = len(arr)
M = len(arr[0])
K = 3
 
findSum(arr, N, M, K)
 
# This code is contributed by rameshtravel07.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to find the maximum sum of K
    // elements from the matrix
    static int maximumSum(int[,] prefixSum, int K, int N, int rem, int id)
    {
      
      // Stores the maximum sum of K elements
      int ans = Int32.MinValue;
      
      // Base Case
      if (rem == 0) return 0;
      
      if (id >= N || rem < 0) return Int32.MinValue;
      
      // Iterate over K elements and find
      // the maximum sum
      for (int i = 0; i <= K; i++) {
        ans = Math.Max(ans, prefixSum[id,i] + maximumSum(prefixSum, K, N, rem - i, id + 1));
      }
      
      // Return the maximum sum obtained
      return ans;
    }
      
    // Function to find the maximum sum of K
    // element from the given matrix
    static void findSum(List> arr, int N, int K, int P)
    {
      
      // Stores the prefix sum of the matrix
      int[,] prefixSum = new int[N,K + 1];
      for(int i = 0; i < N; i++)
      {
        for(int j = 0; j < K + 1; j++)
        {
            prefixSum[i,j] = 0;
        }
      }
      
      // Sorting the arrays
      for (int i = 0; i < arr.Count; i++) {
        arr[i].Sort();
        arr[i].Reverse();
      }
      
      // Storing prefix sum in matrix prefixSum
      for (int i = 0; i < N; i++) {
        int sum = 0;
        for (int j = 1; j <= K; j++) {
          sum += arr[i][j - 1];
          prefixSum[i,j] = sum;
        }
      }
      
      // Print the maximum sum
      Console.Write(maximumSum(prefixSum, K, N, P, 0));
    }
 
  static void Main() {
    List> arr = new List>();
    arr.Add(new List(new int[]{80, 80}));
    arr.Add(new List(new int[]{15, 50}));
    arr.Add(new List(new int[]{20, 10}));
    int N = arr.Count;
    int M = arr[0].Count;
    int K = 3;
  
    findSum(arr, N, M, K);
  }
}
 
// This code is contributed by mukesh07.


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum sum of K
// elements from the matrix
int maximumSum(vector >& prefixSum,
               vector >& dp,
               int K, int N, int rem, int id)
{
    // Stores the maximum sum of K elements
    int ans = INT_MIN;
 
    // Base Case
    if (rem == 0)
        return 0;
 
    if (id >= N || rem < 0)
        return INT_MIN;
 
    if (dp[id][rem] != -1)
        return dp[id][rem];
 
    // Iterate over K elements and find
    // the maximum sum
    for (int i = 0; i <= K; i++) {
        ans = max(ans, prefixSum[id][i]
                           + maximumSum(prefixSum, dp, K, N,
                                        rem - i, id + 1));
    }
 
    // Return the maximum sum obtained
    return ans;
}
 
// Function to find the maximum sum of K
// element from the given matrix
void findSum(vector >& arr,
             int N, int K, int P)
{
 
    // Stores the prefix sum of the matrix
    vector > prefixSum(N,
                                   vector(K + 1, 0));
    vector > dp(N, vector(P + 1, -1));
 
    // Sorting the arrays
    for (int i = 0; i < arr.size(); i++) {
        sort(arr[i].begin(), arr[i].end(),
             greater());
    }
 
    // Storing prefix sum in matrix prefixSum
    for (int i = 0; i < N; i++) {
        int sum = 0;
        for (int j = 1; j <= K; j++) {
            sum += arr[i][j - 1];
            prefixSum[i][j] = sum;
        }
    }
 
    // Print the maximum sum
    cout << maximumSum(prefixSum, dp, K, N, P, 0);
}
 
// Driver Code
int main()
{
    vector > arr
        = { { 80, 80 }, { 15, 50 }, { 20, 10 } };
    int N = arr.size();
    int M = arr[0].size();
    int K = 3;
 
    findSum(arr, N, M, K);
 
    return 0;
}


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum sum of K
// element from the given matrix
void maximumSum(vector >& arr,
                int N, int M, int K)
{
 
    vector allArr(N * M, 0);
 
    // Store all matrix elements
    int id = 0;
 
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < K; j++) {
            allArr[id] = arr[i][j];
            id++;
        }
    }
 
    // Sort the array
    sort(allArr.begin(), allArr.end(),
         greater());
 
    // Stores the maximum sum
    int ans = 0;
 
    // Find the maximum sum
    for (int i = 0; i < K; i++) {
        ans += allArr[i];
    }
 
    // Print the maximum sum
    cout << ans;
}
 
// Driver Code
int main()
{
    vector > arr
        = { { 80, 80 }, { 15, 50 }, { 20, 10 } };
    int N = arr.size();
    int M = arr[0].size();
    int K = 3;
 
    maximumSum(arr, N, M, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
public class GFG
{
    static int[][] arr = { { 80, 80 }, { 15, 50 }, { 20, 10 } };
      
    // Function to find the maximum sum of K
    // element from the given matrix
    static void maximumSum(int N, int M, int K)
    {
   
        int[] allArr = new int[N * M];
   
        // Store all matrix elements
        int id = 0;
   
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                allArr[id] = arr[i][j];
                id++;
            }
        }
   
        // Sort the array
        Arrays.sort(allArr);
        for(int i = 0; i < allArr.length/2; i++)
        {
            int temp = allArr[i];
            allArr[i] = allArr[allArr.length -i-1];
            allArr[allArr.length -i-1] = temp;
        }
   
        // Stores the maximum sum
        int ans = 0;
   
        // Find the maximum sum
        for (int i = 0; i < K; i++) {
            ans += allArr[i];
        }
   
        // Print the maximum sum
        System.out.print(ans);
    }
     
  // Driver code
    public static void main(String[] args) {
        int N = 3;
        int M = 2;
        int K = 3;
        
        maximumSum(N, M, K);
    }
}
 
// This code is contributed by decode2207.


Python3
# Python3 program for the above approach
arr = [ [ 80, 80 ], [ 15, 50 ], [ 20, 10 ] ]
      
# Function to find the maximum sum of K
# element from the given matrix
def maximumSum(N, M, K):
    allArr = [0]*(N * M)
 
    # Store all matrix elements
    Id = 0
 
    for i in range(N):
        for j in range(M):
            allArr[Id] = arr[i][j]
            Id += 1
 
    # Sort the array
    allArr.sort()
    allArr.reverse()
 
    # Stores the maximum sum
    ans = 0
 
    # Find the maximum sum
    for i in range(K):
        ans += allArr[i]
 
    # Print the maximum sum
    print(ans)
 
    # Driver code
N = 3
M = 2
K = 3
 
maximumSum(N, M, K)
 
# This code is contributed by suresh07.


C#
// C# program for the above approach
using System;
class GFG {
     
    static int[,] arr = { { 80, 80 }, { 15, 50 }, { 20, 10 } };
     
    // Function to find the maximum sum of K
    // element from the given matrix
    static void maximumSum(int N, int M, int K)
    {
  
        int[] allArr = new int[N * M];
  
        // Store all matrix elements
        int id = 0;
  
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                allArr[id] = arr[i,j];
                id++;
            }
        }
  
        // Sort the array
        Array.Sort(allArr);
        Array.Reverse(allArr);
  
        // Stores the maximum sum
        int ans = 0;
  
        // Find the maximum sum
        for (int i = 0; i < K; i++) {
            ans += allArr[i];
        }
  
        // Print the maximum sum
        Console.Write(ans);
    }
   
  // Driver code
  static void Main() {
    int N = 3;
    int M = 2;
    int K = 3;
   
    maximumSum(N, M, K);
  }
}
 
// This code is contributed by divyesh072019.


Javascript


输出:
210

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

高效方法:上述方法也可以通过将重叠子问题存储在二维数组中进行优化,并使用循环状态的结果来降低时间复杂度。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum sum of K
// elements from the matrix
int maximumSum(vector >& prefixSum,
               vector >& dp,
               int K, int N, int rem, int id)
{
    // Stores the maximum sum of K elements
    int ans = INT_MIN;
 
    // Base Case
    if (rem == 0)
        return 0;
 
    if (id >= N || rem < 0)
        return INT_MIN;
 
    if (dp[id][rem] != -1)
        return dp[id][rem];
 
    // Iterate over K elements and find
    // the maximum sum
    for (int i = 0; i <= K; i++) {
        ans = max(ans, prefixSum[id][i]
                           + maximumSum(prefixSum, dp, K, N,
                                        rem - i, id + 1));
    }
 
    // Return the maximum sum obtained
    return ans;
}
 
// Function to find the maximum sum of K
// element from the given matrix
void findSum(vector >& arr,
             int N, int K, int P)
{
 
    // Stores the prefix sum of the matrix
    vector > prefixSum(N,
                                   vector(K + 1, 0));
    vector > dp(N, vector(P + 1, -1));
 
    // Sorting the arrays
    for (int i = 0; i < arr.size(); i++) {
        sort(arr[i].begin(), arr[i].end(),
             greater());
    }
 
    // Storing prefix sum in matrix prefixSum
    for (int i = 0; i < N; i++) {
        int sum = 0;
        for (int j = 1; j <= K; j++) {
            sum += arr[i][j - 1];
            prefixSum[i][j] = sum;
        }
    }
 
    // Print the maximum sum
    cout << maximumSum(prefixSum, dp, K, N, P, 0);
}
 
// Driver Code
int main()
{
    vector > arr
        = { { 80, 80 }, { 15, 50 }, { 20, 10 } };
    int N = arr.size();
    int M = arr[0].size();
    int K = 3;
 
    findSum(arr, N, M, K);
 
    return 0;
}
输出:
210

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

优化方法:上述方法也可以通过将所有矩阵元素存储在另一个数组arr[]中进行优化,然后对数组进行降序排序并打印前K个元素的总和作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum sum of K
// element from the given matrix
void maximumSum(vector >& arr,
                int N, int M, int K)
{
 
    vector allArr(N * M, 0);
 
    // Store all matrix elements
    int id = 0;
 
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < K; j++) {
            allArr[id] = arr[i][j];
            id++;
        }
    }
 
    // Sort the array
    sort(allArr.begin(), allArr.end(),
         greater());
 
    // Stores the maximum sum
    int ans = 0;
 
    // Find the maximum sum
    for (int i = 0; i < K; i++) {
        ans += allArr[i];
    }
 
    // Print the maximum sum
    cout << ans;
}
 
// Driver Code
int main()
{
    vector > arr
        = { { 80, 80 }, { 15, 50 }, { 20, 10 } };
    int N = arr.size();
    int M = arr[0].size();
    int K = 3;
 
    maximumSum(arr, N, M, K);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
public class GFG
{
    static int[][] arr = { { 80, 80 }, { 15, 50 }, { 20, 10 } };
      
    // Function to find the maximum sum of K
    // element from the given matrix
    static void maximumSum(int N, int M, int K)
    {
   
        int[] allArr = new int[N * M];
   
        // Store all matrix elements
        int id = 0;
   
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                allArr[id] = arr[i][j];
                id++;
            }
        }
   
        // Sort the array
        Arrays.sort(allArr);
        for(int i = 0; i < allArr.length/2; i++)
        {
            int temp = allArr[i];
            allArr[i] = allArr[allArr.length -i-1];
            allArr[allArr.length -i-1] = temp;
        }
   
        // Stores the maximum sum
        int ans = 0;
   
        // Find the maximum sum
        for (int i = 0; i < K; i++) {
            ans += allArr[i];
        }
   
        // Print the maximum sum
        System.out.print(ans);
    }
     
  // Driver code
    public static void main(String[] args) {
        int N = 3;
        int M = 2;
        int K = 3;
        
        maximumSum(N, M, K);
    }
}
 
// This code is contributed by decode2207.

Python3

# Python3 program for the above approach
arr = [ [ 80, 80 ], [ 15, 50 ], [ 20, 10 ] ]
      
# Function to find the maximum sum of K
# element from the given matrix
def maximumSum(N, M, K):
    allArr = [0]*(N * M)
 
    # Store all matrix elements
    Id = 0
 
    for i in range(N):
        for j in range(M):
            allArr[Id] = arr[i][j]
            Id += 1
 
    # Sort the array
    allArr.sort()
    allArr.reverse()
 
    # Stores the maximum sum
    ans = 0
 
    # Find the maximum sum
    for i in range(K):
        ans += allArr[i]
 
    # Print the maximum sum
    print(ans)
 
    # Driver code
N = 3
M = 2
K = 3
 
maximumSum(N, M, K)
 
# This code is contributed by suresh07.

C#

// C# program for the above approach
using System;
class GFG {
     
    static int[,] arr = { { 80, 80 }, { 15, 50 }, { 20, 10 } };
     
    // Function to find the maximum sum of K
    // element from the given matrix
    static void maximumSum(int N, int M, int K)
    {
  
        int[] allArr = new int[N * M];
  
        // Store all matrix elements
        int id = 0;
  
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                allArr[id] = arr[i,j];
                id++;
            }
        }
  
        // Sort the array
        Array.Sort(allArr);
        Array.Reverse(allArr);
  
        // Stores the maximum sum
        int ans = 0;
  
        // Find the maximum sum
        for (int i = 0; i < K; i++) {
            ans += allArr[i];
        }
  
        // Print the maximum sum
        Console.Write(ans);
    }
   
  // Driver code
  static void Main() {
    int N = 3;
    int M = 2;
    int K = 3;
   
    maximumSum(N, M, K);
  }
}
 
// This code is contributed by divyesh072019.

Javascript


输出:
210

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