📌  相关文章
📜  通过反转第一个数组中的最多一个子数组来最大化两个数组中相应索引处的乘积之和

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

通过反转第一个数组中的最多一个子数组来最大化两个数组中相应索引处的乘积之和

给定两个大小为N的数组AB ,任务是通过反转数组A的最多一个子数组来最大化从0N-1的所有i值的A[i]*B[i]的总和。

例子:

朴素方法:解决此问题的一种简单方法是检查 A 的所有可能子数组并将它们一一反转以找到总和的最大可能值。

下面是上述方法的实现:

C++
// C++ program of the above approach
 
#include 
using namespace std;
 
// Function to find the maximum sum of A[i]*B[i]
// across all values of i from 0 to N-1 by reversing
// at most one subarray of array A
int maxSum(vector& A, vector& B)
{
    int N = A.size();
 
    // Initialising maximum possible sum variable
    int maxPosSum = 0;
 
    // Iterating for all subarrays
    for (int L = 0; L < N - 1; L++) {
        for (int R = L; R < N; R++) {
 
            // Variable for storing the sum after reversing
            // The subarray from L to R
            int curSum = 0;
            for (int i = 0; i < N; i++) {
 
                // Checking if the current index is in the
                // reversed subarray
                if (i >= L && i <= R)
                    curSum += A[L + R - i] * B[i];
                else
                    curSum += A[i] * B[i];
            }
 
            // Updating the answer
            maxPosSum = max(maxPosSum, curSum);
        }
    }
 
    // Returning the Maximum Possible Sum of product
    return maxPosSum;
}
 
// Driver Code
int main()
{
    // Given Input
    int N = 4;
    vector A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 };
 
    cout << maxSum(A, B);
}


Java
// Java code to implement above approach
import java.util.*;
public class GFG {
 
  // Function to find the maximum sum of A[i]*B[i]
  // across all values of i from 0 to N-1 by reversing
  // at most one subarray of array A
  static int maxSum(int []A, int []B)
  {
    int N = A.length;
 
    // Initialising maximum possible sum variable
    int maxPosSum = 0;
 
    // Iterating for all subarrays
    for (int L = 0; L < N - 1; L++) {
      for (int R = L; R < N; R++) {
 
        // Variable for storing the sum after reversing
        // The subarray from L to R
        int curSum = 0;
        for (int i = 0; i < N; i++) {
 
          // Checking if the current index is in the
          // reversed subarray
          if (i >= L && i <= R)
            curSum += A[L + R - i] * B[i];
          else
            curSum += A[i] * B[i];
        }
 
        // Updating the answer
        maxPosSum = Math.max(maxPosSum, curSum);
      }
    }
 
    // Returning the Maximum Possible Sum of product
    return maxPosSum;
  }
 
  // Driver code
  public static void main(String args[])
  {
     
    // Given Input
    int N = 4;
    int []A = { 5, 1, 2, 3 };
    int []B = { 1, 4, 3, 2 };
    System.out.println(maxSum(A, B));
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3
# Python code for the above approach
 
# Function to find the maximum sum of A[i]*B[i]
# across all values of i from 0 to N-1 by reversing
# at most one subarray of array A
def maxSum(A, B):
    N = len(A)
 
    # Initialising maximum possible sum variable
    maxPosSum = 0
 
    # Iterating for all subarrays
    for L in range(N - 1):
        for R in range(L, N):
 
            # Variable for storing the sum after reversing
            # The subarray from L to R
            curSum = 0
            for i in range(N):
                # Checking if the current index is in the
                # reversed subarray
                if (i >= L and i <= R):
                    curSum += A[L + R - i] * B[i]
                else:
                    curSum += A[i] * B[i]
 
            # Updating the answer
            maxPosSum = max(maxPosSum, curSum)
 
    # Returning the Maximum Possible Sum of product
    return maxPosSum
 
# Driver Code
 
# Given Input
N = 4
A = [5, 1, 2, 3]
B = [1, 4, 3, 2]
print(maxSum(A, B))
 
# This code is contributed by gfgking


C#
// C# code to implement above approach
using System;
public class GFG {
 
  // Function to find the maximum sum of A[i]*B[i]
  // across all values of i from 0 to N-1 by reversing
  // at most one subarray of array A
  static int maxSum(int []A, int []B)
  {
    int N = A.Length;
 
    // Initialising maximum possible sum variable
    int maxPosSum = 0;
 
    // Iterating for all subarrays
    for (int L = 0; L < N - 1; L++) {
      for (int R = L; R < N; R++) {
 
        // Variable for storing the sum after reversing
        // The subarray from L to R
        int curSum = 0;
        for (int i = 0; i < N; i++) {
 
          // Checking if the current index is in the
          // reversed subarray
          if (i >= L && i <= R)
            curSum += A[L + R - i] * B[i];
          else
            curSum += A[i] * B[i];
        }
 
        // Updating the answer
        maxPosSum = Math.Max(maxPosSum, curSum);
      }
    }
 
    // Returning the Maximum Possible Sum of product
    return maxPosSum;
  }
 
  // Driver code
  public static void Main()
  {
     
    // Given Input
    int []A = { 5, 1, 2, 3 };
    int []B = { 1, 4, 3, 2 };
    Console.Write(maxSum(A, B));
 
  }
}
 
// This code is contributed by Saurabh Jaiswal


Javascript


C++
// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to find the maximum sum of A[i]*B[i]
// across all values of i from 0 to N-1 by reversing
// at most one subarray of array A
int maxSum(vector& A, vector& B)
{
 
    int N = A.size();
 
    // Initialising maximum possible sum variable
    int maxPosSum = 0;
    int dp[N][N];
 
    // Initialising the dp array
    memset(dp, 0, sizeof(dp));
 
    // Value of maxPosSum when no subarray is reversed
    for (int i = 0; i < N; i++)
        maxPosSum += A[i] * B[i];
 
    // Initialising dp for subarray of length 1
    for (int i = 0; i < N; i++)
        dp[i][i] = maxPosSum;
 
    // Initialising dp for subarray of length 2
    for (int i = 0; i < N - 1; i++) {
        int R = i + 1;
        int L = i;
        dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L])
                   + (A[L] * B[R]) - (A[R] * B[R]);
    }
 
    // Calculating the complete dp array
    for (int R = 0; R < N; R++) {
        for (int L = 0; L < N; L++) {
 
            // If length of subarray is less 3, then
            // continuing
            if (R - L + 1 < 3)
                continue;
            dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L])
                       - (A[L] * B[L]) + (A[L] * B[R])
                       - (A[R] * B[R]);
        }
    }
 
    // Updating the maxPosSum variable
    for (int L = 0; L < N; L++) {
        for (int R = L; R < N; R++) {
            maxPosSum = max(maxPosSum, dp[L][R]);
        }
    }
 
    // Returning the maximum possible sum of product
    return maxPosSum;
}
 
// Driver Code
int main()
{
    // Given Input
    vector A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 };
 
    cout << maxSum(A, B);
    return 0;
}


Java
// Java implementation of the above approach
import java.util.*;
 
class GFG{
 
// Function to find the maximum sum of A[i]*B[i]
// across all values of i from 0 to N-1 by reversing
// at most one subarray of array A
static int maxSum(int[] A, int[] B)
{
 
    int N = A.length;
 
    // Initialising maximum possible sum variable
    int maxPosSum = 0;
    int [][]dp = new int[N][N];
 
 
    // Value of maxPosSum when no subarray is reversed
    for (int i = 0; i < N; i++)
        maxPosSum += A[i] * B[i];
 
    // Initialising dp for subarray of length 1
    for (int i = 0; i < N; i++)
        dp[i][i] = maxPosSum;
 
    // Initialising dp for subarray of length 2
    for (int i = 0; i < N - 1; i++) {
        int R = i + 1;
        int L = i;
        dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L])
                   + (A[L] * B[R]) - (A[R] * B[R]);
    }
 
    // Calculating the complete dp array
    for (int R = 0; R < N; R++) {
        for (int L = 0; L < N; L++) {
 
            // If length of subarray is less 3, then
            // continuing
            if (R - L + 1 < 3)
                continue;
            dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L])
                       - (A[L] * B[L]) + (A[L] * B[R])
                       - (A[R] * B[R]);
        }
    }
 
    // Updating the maxPosSum variable
    for (int L = 0; L < N; L++) {
        for (int R = L; R < N; R++) {
            maxPosSum = Math.max(maxPosSum, dp[L][R]);
        }
    }
 
    // Returning the maximum possible sum of product
    return maxPosSum;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given Input
    int[] A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 };
 
    System.out.print(maxSum(A, B));
}
}
 
// This code is contributed by 29AjayKumar


Python
# Python implementation of the above approach
 
# Function to find the maximum sum of A[i]*B[i]
# across all values of i from 0 to N-1 by reversing
# at most one subarray of array A
def maxSum(A, B):
 
    N = len(A)
 
    # Initialising maximum possible sum variable
    maxPosSum = 0
 
    # Initialising the dp array
    dp = ([[0 for i in range(N)]
           for i in range(N)])
 
    # Value of maxPosSum when no subarray is reversed
    for i in range(0, N):
        maxPosSum = maxPosSum + (A[i] * B[i])
 
    # Initialising dp for subarray of length 1
    for i in range(0, N):
        dp[i][i] = maxPosSum
 
    # Initialising dp for subarray of length 2
    for i in range(0, N - 1):
        R = i + 1
        L = i
        dp[L][R] = maxPosSum + (A[R] * B[L]) - \
            (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R])
 
    # Calculating the complete dp array
    for R in range(0, N):
        for L in range(0, N):
 
            # If length of subarray is less 3, then
            # continuing
            if (R - L + 1 < 3):
                continue
            dp[L][R] = dp[L + 1][R - 1] + \
                (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R])
 
    # Updating the maxPosSum variable
    for R in range(0, N):
        for L in range(0, N):
            maxPosSum = max(maxPosSum, dp[L][R])
 
    # Returning the maximum possible sum of product
    return maxPosSum
 
# Driver Code
# Given Input
A = [5, 1, 2, 3]
B = [1, 4, 3, 2]
 
print(maxSum(A, B))
 
# This code is contributed by Samim Hossain Mondal.


C#
// C# implementation of the above approach
using System;
class GFG {
 
    // Function to find the maximum sum of A[i]*B[i]
    // across all values of i from 0 to N-1 by reversing
    // at most one subarray of array A
    static int maxSum(int[] A, int[] B)
    {
 
        int N = A.Length;
 
        // Initialising maximum possible sum variable
        int maxPosSum = 0;
        int[, ] dp = new int[N, N];
 
        // Initialising the dp array
        // memset(dp, 0, sizeof(dp));
 
        // Value of maxPosSum when no subarray is reversed
        for (int i = 0; i < N; i++)
            maxPosSum += A[i] * B[i];
 
        // Initialising dp for subarray of length 1
        for (int i = 0; i < N; i++)
            dp[i, i] = maxPosSum;
 
        // Initialising dp for subarray of length 2
        for (int i = 0; i < N - 1; i++) {
            int R = i + 1;
            int L = i;
            dp[L, R] = maxPosSum + (A[R] * B[L])
                       - (A[L] * B[L]) + (A[L] * B[R])
                       - (A[R] * B[R]);
        }
 
        // Calculating the complete dp array
        for (int R = 0; R < N; R++) {
            for (int L = 0; L < N; L++) {
 
                // If length of subarray is less 3, then
                // continuing
                if (R - L + 1 < 3)
                    continue;
                dp[L, R] = dp[L + 1, R - 1] + (A[R] * B[L])
                           - (A[L] * B[L]) + (A[L] * B[R])
                           - (A[R] * B[R]);
            }
        }
 
        // Updating the maxPosSum variable
        for (int L = 0; L < N; L++) {
            for (int R = L; R < N; R++) {
                maxPosSum = Math.Max(maxPosSum, dp[L, R]);
            }
        }
 
        // Returning the maximum possible sum of product
        return maxPosSum;
    }
 
    // Driver Code
    public static void Main()
    {
        // Given Input
        int[] A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 };
 
        Console.WriteLine(maxSum(A, B));
    }
}
 
// This code is contributed by ukasp.


Javascript



输出
33

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

有效方法:上述问题可以通过使用动态规划来解决。请按照以下步骤解决此问题:

  • 令 dp[L][[R] 表示 A[i] 和 B[i] 在反转子数组 A[L, R] 后的乘积之和。
  • 观察如果子数组 A[L, R] 颠倒,子数组 A[L+1, R-1] 也颠倒。因此,可以使用 dp[L+1][R-1] 并使用以下公式计算 dp[L][R]:
  • 因为 dp[L+1][R-1]的计算中,添加了 A[L]*B[L]A[R]*B[R]而对于计算dp[L][R]A添加了[R]*B[L]A[L]*B[R ]。
  • 因此我们需要减去A[L]*B[L]A[R]*B[R]并将A[R]*B[L]A[L]*B[R]添加到dp[L+ 1][R-1]用于计算dp[L][R]
  • 根据以上观察打印答案。

下面是动态规划方法的实现。

C++

// C++ implementation of the above approach
#include 
using namespace std;
 
// Function to find the maximum sum of A[i]*B[i]
// across all values of i from 0 to N-1 by reversing
// at most one subarray of array A
int maxSum(vector& A, vector& B)
{
 
    int N = A.size();
 
    // Initialising maximum possible sum variable
    int maxPosSum = 0;
    int dp[N][N];
 
    // Initialising the dp array
    memset(dp, 0, sizeof(dp));
 
    // Value of maxPosSum when no subarray is reversed
    for (int i = 0; i < N; i++)
        maxPosSum += A[i] * B[i];
 
    // Initialising dp for subarray of length 1
    for (int i = 0; i < N; i++)
        dp[i][i] = maxPosSum;
 
    // Initialising dp for subarray of length 2
    for (int i = 0; i < N - 1; i++) {
        int R = i + 1;
        int L = i;
        dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L])
                   + (A[L] * B[R]) - (A[R] * B[R]);
    }
 
    // Calculating the complete dp array
    for (int R = 0; R < N; R++) {
        for (int L = 0; L < N; L++) {
 
            // If length of subarray is less 3, then
            // continuing
            if (R - L + 1 < 3)
                continue;
            dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L])
                       - (A[L] * B[L]) + (A[L] * B[R])
                       - (A[R] * B[R]);
        }
    }
 
    // Updating the maxPosSum variable
    for (int L = 0; L < N; L++) {
        for (int R = L; R < N; R++) {
            maxPosSum = max(maxPosSum, dp[L][R]);
        }
    }
 
    // Returning the maximum possible sum of product
    return maxPosSum;
}
 
// Driver Code
int main()
{
    // Given Input
    vector A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 };
 
    cout << maxSum(A, B);
    return 0;
}

Java

// Java implementation of the above approach
import java.util.*;
 
class GFG{
 
// Function to find the maximum sum of A[i]*B[i]
// across all values of i from 0 to N-1 by reversing
// at most one subarray of array A
static int maxSum(int[] A, int[] B)
{
 
    int N = A.length;
 
    // Initialising maximum possible sum variable
    int maxPosSum = 0;
    int [][]dp = new int[N][N];
 
 
    // Value of maxPosSum when no subarray is reversed
    for (int i = 0; i < N; i++)
        maxPosSum += A[i] * B[i];
 
    // Initialising dp for subarray of length 1
    for (int i = 0; i < N; i++)
        dp[i][i] = maxPosSum;
 
    // Initialising dp for subarray of length 2
    for (int i = 0; i < N - 1; i++) {
        int R = i + 1;
        int L = i;
        dp[L][R] = maxPosSum + (A[R] * B[L]) - (A[L] * B[L])
                   + (A[L] * B[R]) - (A[R] * B[R]);
    }
 
    // Calculating the complete dp array
    for (int R = 0; R < N; R++) {
        for (int L = 0; L < N; L++) {
 
            // If length of subarray is less 3, then
            // continuing
            if (R - L + 1 < 3)
                continue;
            dp[L][R] = dp[L + 1][R - 1] + (A[R] * B[L])
                       - (A[L] * B[L]) + (A[L] * B[R])
                       - (A[R] * B[R]);
        }
    }
 
    // Updating the maxPosSum variable
    for (int L = 0; L < N; L++) {
        for (int R = L; R < N; R++) {
            maxPosSum = Math.max(maxPosSum, dp[L][R]);
        }
    }
 
    // Returning the maximum possible sum of product
    return maxPosSum;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given Input
    int[] A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 };
 
    System.out.print(maxSum(A, B));
}
}
 
// This code is contributed by 29AjayKumar

Python

# Python implementation of the above approach
 
# Function to find the maximum sum of A[i]*B[i]
# across all values of i from 0 to N-1 by reversing
# at most one subarray of array A
def maxSum(A, B):
 
    N = len(A)
 
    # Initialising maximum possible sum variable
    maxPosSum = 0
 
    # Initialising the dp array
    dp = ([[0 for i in range(N)]
           for i in range(N)])
 
    # Value of maxPosSum when no subarray is reversed
    for i in range(0, N):
        maxPosSum = maxPosSum + (A[i] * B[i])
 
    # Initialising dp for subarray of length 1
    for i in range(0, N):
        dp[i][i] = maxPosSum
 
    # Initialising dp for subarray of length 2
    for i in range(0, N - 1):
        R = i + 1
        L = i
        dp[L][R] = maxPosSum + (A[R] * B[L]) - \
            (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R])
 
    # Calculating the complete dp array
    for R in range(0, N):
        for L in range(0, N):
 
            # If length of subarray is less 3, then
            # continuing
            if (R - L + 1 < 3):
                continue
            dp[L][R] = dp[L + 1][R - 1] + \
                (A[R] * B[L]) - (A[L] * B[L]) + (A[L] * B[R]) - (A[R] * B[R])
 
    # Updating the maxPosSum variable
    for R in range(0, N):
        for L in range(0, N):
            maxPosSum = max(maxPosSum, dp[L][R])
 
    # Returning the maximum possible sum of product
    return maxPosSum
 
# Driver Code
# Given Input
A = [5, 1, 2, 3]
B = [1, 4, 3, 2]
 
print(maxSum(A, B))
 
# This code is contributed by Samim Hossain Mondal.

C#

// C# implementation of the above approach
using System;
class GFG {
 
    // Function to find the maximum sum of A[i]*B[i]
    // across all values of i from 0 to N-1 by reversing
    // at most one subarray of array A
    static int maxSum(int[] A, int[] B)
    {
 
        int N = A.Length;
 
        // Initialising maximum possible sum variable
        int maxPosSum = 0;
        int[, ] dp = new int[N, N];
 
        // Initialising the dp array
        // memset(dp, 0, sizeof(dp));
 
        // Value of maxPosSum when no subarray is reversed
        for (int i = 0; i < N; i++)
            maxPosSum += A[i] * B[i];
 
        // Initialising dp for subarray of length 1
        for (int i = 0; i < N; i++)
            dp[i, i] = maxPosSum;
 
        // Initialising dp for subarray of length 2
        for (int i = 0; i < N - 1; i++) {
            int R = i + 1;
            int L = i;
            dp[L, R] = maxPosSum + (A[R] * B[L])
                       - (A[L] * B[L]) + (A[L] * B[R])
                       - (A[R] * B[R]);
        }
 
        // Calculating the complete dp array
        for (int R = 0; R < N; R++) {
            for (int L = 0; L < N; L++) {
 
                // If length of subarray is less 3, then
                // continuing
                if (R - L + 1 < 3)
                    continue;
                dp[L, R] = dp[L + 1, R - 1] + (A[R] * B[L])
                           - (A[L] * B[L]) + (A[L] * B[R])
                           - (A[R] * B[R]);
            }
        }
 
        // Updating the maxPosSum variable
        for (int L = 0; L < N; L++) {
            for (int R = L; R < N; R++) {
                maxPosSum = Math.Max(maxPosSum, dp[L, R]);
            }
        }
 
        // Returning the maximum possible sum of product
        return maxPosSum;
    }
 
    // Driver Code
    public static void Main()
    {
        // Given Input
        int[] A = { 5, 1, 2, 3 }, B = { 1, 4, 3, 2 };
 
        Console.WriteLine(maxSum(A, B));
    }
}
 
// This code is contributed by ukasp.

Javascript



输出
33

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