📌  相关文章
📜  按顺序从两个数组中选取元素的最大总和 | 2套

📅  最后修改于: 2021-09-07 04:36:03             🧑  作者: Mango

给定两个数组A[]B[] ,每个数组的大小为N ,以及两个整数XY 分别表示可以从 A[] 和 B[] 中选取的最大元素数,任务是找到可能的最大值通过选择N 个元素来求和,对于任何索引i ,可以选择 A[i] 或 B[i]。
注意:保证(X + Y) >= N。
例子:

贪婪方法:这篇文章已经讨论了解决这个问题的贪婪方法。
动态规划方法:在本文中,我们将讨论基于动态规划的解决方案。
请按照以下步骤解决问题:

  1. 分钟(N,X)元件可以从A被选择[]分钟(N,Y)元件可以由B []被选择。
  2. 初始化一个二维数组dp[][]使得dp[i][j]包含通过从A[] 中选择i 个元素和从B[]中选择j 个元素(其中 i 和 j 的范围在min (N, X) 内)可能的最大总和和min (N, X)分别。
  3. 初始化变量max_sum以存储可能的最大总和。
  4. 遍历数组,对于每个数组,元素执行以下操作:
    • (i + j)元素可以是A[i + j – 1]B[i + j – 1]
    • 如果从A[] 中选择(i + j)元素,则A[]中第(i + 1)元素的成本将添加到总成本中。因此,在这种情况下,选择第(i + 1)元素的成本是dp[i][j] = dp[ i – 1 ][ j ] + A[ i + j – 1 ]
    • 如果从B[] 中选择(i + j)元素,则选择第(i + 1)元素的成本为dp[i][j] = dp[ i – 1 ][ j ] + B[ i + j – 1 ]
  5. 现在,目标是最大化成本。因此,递推关系为:
  1. 每次迭代后不断更新max_sum 。完成数组遍历后,打印max_sum的最终值。

下面是上述方法的实现:

C++
// C++ program to find maximum sum
// possible by selecting an element
// from one of two arrays for every index
 
#include 
using namespace std;
 
// Function to calculate maximum sum
int maximumSum(int A[], int B[],
               int length,
               int X, int Y)
{
    int l = length;
    // Maximum elements that can be
    // chosen from array A
    int l1 = min(length, X);
 
    // Maximum elements that can be
    // chosen from array B
    int l2 = min(length, Y);
 
    int dp[l1 + 1][l2 + 1];
    memset(dp, 0, sizeof(dp));
    dp[0][0] = 0;
 
    // Stores the maximum
    // sum possible
    int max_sum = INT_MIN;
 
    // Fill the dp[][] for base case when
    // all elements are selected from A[]
    for (int i = 1; i <= l1; i++) {
        dp[i][0] = dp[i - 1][0] + A[i - 1];
        max_sum = max(max_sum, dp[i][0]);
    }
 
    // Fill the dp[][] for base case when
    // all elements are selected from B[]
    for (int i = 1; i <= l2; i++) {
        dp[0][i] = dp[0][i - 1] + B[i - 1];
        max_sum = max(max_sum, dp[0][i]);
    }
 
    for (int i = 1; i <= l1; i++) {
        for (int j = 1; j <= l2; j++) {
            if (i + j <= l)
                dp[i][j]
                    = max(dp[i - 1][j]
                              + A[i + j - 1],
                          dp[i][j - 1]
                              + B[i + j - 1]);
            max_sum = max(dp[i][j],
                          max_sum);
        }
    }
 
    // Return the final answer
    return max_sum;
}
 
// Driver Program
int main()
{
    int A[] = { 1, 2, 3, 4, 5 };
    int B[] = { 5, 4, 3, 2, 1 };
    int X = 3, Y = 2;
 
    int N = sizeof(A) / sizeof(A[0]);
 
    cout << maximumSum(A, B, N, X, Y);
 
    return 0;
}


Java
// Java program to find maximum sum
// possible by selecting an element
// from one of two arrays for every index
class GFG{
     
// Function to calculate maximum sum
static int maximumSum(int A[], int B[],
                      int length, int X,
                      int Y)
{
    int l = length;
     
    // Maximum elements that can be
    // chosen from array A
    int l1 = Math.min(length, X);
 
    // Maximum elements that can be
    // chosen from array B
    int l2 = Math.min(length, Y);
 
    int dp[][] = new int [l1 + 1][l2 + 1];
 
    // Stores the maximum
    // sum possible
    int max_sum = Integer.MIN_VALUE;
 
    // Fill the dp[][] for base case when
    // all elements are selected from A[]
    for(int i = 1; i <= l1; i++)
    {
        dp[i][0] = dp[i - 1][0] + A[i - 1];
        max_sum = Math.max(max_sum, dp[i][0]);
    }
 
    // Fill the dp[][] for base case when
    // all elements are selected from B[]
    for(int i = 1; i <= l2; i++)
    {
        dp[0][i] = dp[0][i - 1] + B[i - 1];
        max_sum = Math.max(max_sum, dp[0][i]);
    }
 
    for(int i = 1; i <= l1; i++)
    {
        for(int j = 1; j <= l2; j++)
        {
            if (i + j <= l)
                dp[i][j] = Math.max(dp[i - 1][j] +
                                     A[i + j - 1],
                                    dp[i][j - 1] +
                                     B[i + j - 1]);
            max_sum = Math.max(dp[i][j], max_sum);
        }
    }
     
    // Return the final answer
    return max_sum;
}
     
// Driver code
public static void main (String[] args)
{
    int A[] = new int[]{ 1, 2, 3, 4, 5 };
    int B[] = new int[]{ 5, 4, 3, 2, 1 };
     
    int X = 3, Y = 2;
    int N = A.length;
 
    System.out.println(maximumSum(A, B, N, X, Y));
}
}
 
// This code is contributed by Pratima Pandey


Python
# Python3 program to find maximum sum
# possible by selecting an element
# from one of two arrays for every index
# Function to calculate maximum sum
def maximumSum(A, B, length, X, Y):
    l = length
     
    # Maximum elements that can be
    # chosen from array A
    l1 = min(length, X)
 
    # Maximum elements that can be
    # chosen from array B
    l2 = min(length, Y)
 
    dp=[[ 0 for i in range(l2 + 1)]
        for i in range(l1 + 1)]
    dp[0][0] = 0
 
    # Stores the maximum
    # sum possible
    max_sum = -10 * 9
 
    # Fill the dp[]for base case when
    # all elements are selected from A[]
    for i in range(1, l1 + 1):
        dp[i][0] = dp[i - 1][0] + A[i - 1]
        max_sum = max(max_sum, dp[i][0])
 
 
    # Fill the dp[]for base case when
    # all elements are selected from B[]
    for i in range(1, l2 + 1):
        dp[0][i] = dp[0][i - 1] + B[i - 1]
        max_sum = max(max_sum, dp[0][i])
 
    for i in range(1, l1 + 1):
        for j in range(1, l2 + 1):
            if (i + j <= l):
                dp[i][j]= max(dp[i - 1][j] + A[i + j - 1],
                              dp[i][j - 1] + B[i + j - 1])
            max_sum = max(dp[i][j], max_sum)
 
    # Return the final answer
    return max_sum
 
# Driver Program
if __name__ == '__main__':
    A=  [1, 2, 3, 4, 5]
    B=  [5, 4, 3, 2, 1]
    X = 3
    Y = 2
    N = len(A)
    print(maximumSum(A, B, N, X, Y))
 
# This code is contributed by Mohit Kumar 29


C#
// C# program to find maximum sum
// possible by selecting an element
// from one of two arrays for every index
using System;
 
class GFG{
     
// Function to calculate maximum sum
static int maximumSum(int []A, int []B,
                      int length, int X,
                      int Y)
{
    int l = length;
     
    // Maximum elements that can be
    // chosen from array A
    int l1 = Math.Min(length, X);
 
    // Maximum elements that can be
    // chosen from array B
    int l2 = Math.Min(length, Y);
 
    int [,]dp = new int [l1 + 1, l2 + 1];
 
    // Stores the maximum
    // sum possible
    int max_sum = int.MinValue;
 
    // Fill the [,]dp for base case when
    // all elements are selected from []A
    for(int i = 1; i <= l1; i++)
    {
        dp[i, 0] = dp[i - 1, 0] + A[i - 1];
        max_sum = Math.Max(max_sum, dp[i, 0]);
    }
 
    // Fill the [,]dp for base case when
    // all elements are selected from []B
    for(int i = 1; i <= l2; i++)
    {
        dp[0, i] = dp[0, i - 1] + B[i - 1];
        max_sum = Math.Max(max_sum, dp[0, i]);
    }
 
    for(int i = 1; i <= l1; i++)
    {
        for(int j = 1; j <= l2; j++)
        {
            if (i + j <= l)
                dp[i, j] = Math.Max(dp[i - 1, j] +
                                     A[i + j - 1],
                                    dp[i, j - 1] +
                                     B[i + j - 1]);
            max_sum = Math.Max(dp[i, j], max_sum);
        }
    }
     
    // Return the readonly answer
    return max_sum;
}
     
// Driver code
public static void Main(String[] args)
{
    int []A = new int[]{ 1, 2, 3, 4, 5 };
    int []B = new int[]{ 5, 4, 3, 2, 1 };
     
    int X = 3, Y = 2;
    int N = A.Length;
 
    Console.WriteLine(maximumSum(A, B, N, X, Y));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
21

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

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