📌  相关文章
📜  最大化从两个给定数组中选择的相同索引子数组的分数

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

最大化从两个给定数组中选择的相同索引子数组的分数

给定两个数组A[]B[] ,都由N个正整数组成,任务是在两个数组中所有可能的相同索引子数组中找到最大分数,使得任何子数组的分数在[L, R]由值的最大值计算(A L *B L + A L + 1 *B L + 1 + … + A R *B R ) + (A R *B L + A R – 1 *B L + 1 + … + A L *B R )

例子:

朴素方法:解决给定问题的最简单方法是生成所有可能的对应子数组并存储使用给定标准生成的所有子数组的所有分数。存储所有分数后,打印所有生成的分数中的最大值。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to calculate the score
// of same-indexed subarrays selected
// from the arrays a[] and b[]
int currSubArrayScore(int* a, int* b,
                      int l, int r)
{
    int straightScore = 0;
    int reverseScore = 0;
 
    // Traverse the current subarray
    for (int i = l; i <= r; i++) {
 
        // Finding the score without
        // reversing the subarray
        straightScore += a[i] * b[i];
 
        // Calculating the score of
        // the reversed subarray
        reverseScore += a[r - (i - l)]
                        * b[i];
    }
 
    // Return the score of subarray
    return max(straightScore,
               reverseScore);
}
 
// Function to find the subarray with
// the maximum score
void maxScoreSubArray(int* a, int* b,
                      int n)
{
    // Stores the maximum score and the
    // starting and the ending point
    // of subarray with maximum score
    int res = 0, start = 0, end = 0;
 
    // Traverse all the subarrays
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
 
            // Store the score of the
            // current subarray
            int currScore
                = currSubArrayScore(
                    a, b, i, j);
 
            // Update the maximum score
            if (currScore > res) {
                res = currScore;
                start = i;
                end = j;
            }
        }
    }
 
    // Print the maximum score
    cout << res;
}
 
// Driver Code
int main()
{
    int A[] = { 13, 4, 5 };
    int B[] = { 10, 22, 2 };
    int N = sizeof(A) / sizeof(A[0]);
    maxScoreSubArray(A, B, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to calculate the score
// of same-indexed subarrays selected
// from the arrays a[] and b[]
static int currSubArrayScore(int[] a, int[] b,
                             int l, int r)
{
    int straightScore = 0;
    int reverseScore = 0;
 
    // Traverse the current subarray
    for(int i = l; i <= r; i++)
    {
         
        // Finding the score without
        // reversing the subarray
        straightScore += a[i] * b[i];
 
        // Calculating the score of
        // the reversed subarray
        reverseScore += a[r - (i - l)] * b[i];
    }
 
    // Return the score of subarray
    return Math.max(straightScore, reverseScore);
}
 
// Function to find the subarray with
// the maximum score
static void maxScoreSubArray(int[] a, int[] b, int n)
{
     
    // Stores the maximum score and the
    // starting and the ending point
    // of subarray with maximum score
    int res = 0, start = 0, end = 0;
 
    // Traverse all the subarrays
    for(int i = 0; i < n; i++)
    {
        for(int j = i; j < n; j++)
        {
             
            // Store the score of the
            // current subarray
            int currScore = currSubArrayScore(a, b, i, j);
 
            // Update the maximum score
            if (currScore > res)
            {
                res = currScore;
                start = i;
                end = j;
            }
        }
    }
 
    // Print the maximum score
    System.out.print(res);
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 13, 4, 5 };
    int B[] = { 10, 22, 2 };
    int N = A.length;
     
    maxScoreSubArray(A, B, N);
}
}
 
// This code is contributed by subhammahato348


Python3
# Python program for the above approach
 
# Function to calculate the score
# of same-indexed subarrays selected
# from the arrays a[] and b[]
def currSubArrayScore(a, b,
                      l, r):
                           
    straightScore = 0
    reverseScore = 0
 
    # Traverse the current subarray
    for i in range(l, r+1) :
 
        # Finding the score without
        # reversing the subarray
        straightScore += a[i] * b[i]
 
        # Calculating the score of
        # the reversed subarray
        reverseScore += a[r - (i - l)] * b[i]
     
 
    # Return the score of subarray
    return max(straightScore,
               reverseScore)
 
 
# Function to find the subarray with
# the maximum score
def maxScoreSubArray(a, b,
                      n) :
                           
    # Stores the maximum score and the
    # starting and the ending point
    # of subarray with maximum score
    res = 0
    start = 0
    end = 0
 
    # Traverse all the subarrays
    for i in range(n) :
        for j in range(i, n) :
 
            # Store the score of the
            # current subarray
            currScore = currSubArrayScore(a, b, i, j)
 
            # Update the maximum score
            if (currScore > res) :
                res = currScore
                start = i
                end = j
 
    # Print the maximum score
    print(res)
 
# Driver Code
A = [ 13, 4, 5 ]
B = [ 10, 22, 2 ]
N = len(A)
maxScoreSubArray(A, B, N)
 
# This code is contributed by target_2.


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to calculate the score
// of same-indexed subarrays selected
// from the arrays a[] and b[]
static int currSubArrayScore(int[] a, int[] b,
                             int l, int r)
{
    int straightScore = 0;
    int reverseScore = 0;
  
    // Traverse the current subarray
    for(int i = l; i <= r; i++)
    {
         
        // Finding the score without
        // reversing the subarray
        straightScore += a[i] * b[i];
  
        // Calculating the score of
        // the reversed subarray
        reverseScore += a[r - (i - l)] * b[i];
    }
  
    // Return the score of subarray
    return Math.Max(straightScore, reverseScore);
}
  
// Function to find the subarray with
// the maximum score
static void maxScoreSubArray(int[] a, int[] b, int n)
{
     
    // Stores the maximum score and the
    // starting and the ending point
    // of subarray with maximum score
    int res = 0;
  
    // Traverse all the subarrays
    for(int i = 0; i < n; i++)
    {
        for(int j = i; j < n; j++)
        {
             
            // Store the score of the
            // current subarray
            int currScore = currSubArrayScore(
                a, b, i, j);
  
            // Update the maximum score
            if (currScore > res)
            {
                res = currScore;
            }
        }
    }
     
    // Print the maximum score
    Console.Write(res);
}
  
// Driver Code
static public void Main()
{
    int[] A = { 13, 4, 5 };
    int[] B = { 10, 22, 2 };
    int N = A.Length;
     
    maxScoreSubArray(A, B, N);
}
}
 
// This code is contributed by unknown2108


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to calculate the score
// of same-indexed subarrays selected
// from the arrays a[] and b[]
void maxScoreSubArray(int* a, int* b,
                      int n)
{
    // Store the required result
    int res = 0;
 
    // Iterate in the range [0, N-1]
    for (int mid = 0; mid < n; mid++) {
 
        // Consider the case of odd
        // length subarray
        int straightScore = a[mid] * b[mid],
            reverseScore = a[mid] * a[mid];
        int prev = mid - 1, next = mid + 1;
 
        // Update the maximum score
        res = max(res, max(straightScore,
                           reverseScore));
 
        // Expanding the subarray in both
        // directions with equal length
        // so that mid point remains same
        while (prev >= 0 && next < n) {
 
            // Update both the scores
            straightScore
                += (a[prev] * b[prev]
                    + a[next] * b[next]);
            reverseScore
                += (a[prev] * b[next]
                    + a[next] * b[prev]);
 
            res = max(res,
                      max(straightScore,
                          reverseScore));
 
            prev--;
            next++;
        }
 
        // Consider the case of
        // even length subarray
        straightScore = 0;
        reverseScore = 0;
 
        prev = mid - 1, next = mid;
        while (prev >= 0 && next < n) {
 
            // Update both the scores
            straightScore
                += (a[prev] * b[prev]
                    + a[next] * b[next]);
            reverseScore
                += (a[prev] * b[next]
                    + a[next] * b[prev]);
 
            res = max(res,
                      max(straightScore,
                          reverseScore));
 
            prev--;
            next++;
        }
    }
 
    // Print the result
    cout << res;
}
 
// Driver Code
int main()
{
    int A[] = { 13, 4, 5 };
    int B[] = { 10, 22, 2 };
    int N = sizeof(A) / sizeof(A[0]);
    maxScoreSubArray(A, B, N);
 
    return 0;
}


Java
// Java Program for the above approach
import java.io.*;
 
class GFG {
    // Function to calculate the score
    // of same-indexed subarrays selected
    // from the arrays a[] and b[]
    static void maxScoreSubArray(int[] a, int[] b, int n)
    {
        // Store the required result
        int res = 0;
 
        // Iterate in the range [0, N-1]
        for (int mid = 0; mid < n; mid++) {
 
            // Consider the case of odd
            // length subarray
            int straightScore = a[mid] * b[mid],
                reverseScore = a[mid] * a[mid];
            int prev = mid - 1, next = mid + 1;
 
            // Update the maximum score
            res = Math.max(
                res, Math.max(straightScore, reverseScore));
 
            // Expanding the subarray in both
            // directions with equal length
            // so that mid point remains same
            while (prev >= 0 && next < n) {
 
                // Update both the scores
                straightScore += (a[prev] * b[prev]
                                  + a[next] * b[next]);
                reverseScore += (a[prev] * b[next]
                                 + a[next] * b[prev]);
 
                res = Math.max(res, Math.max(straightScore,
                                             reverseScore));
 
                prev--;
                next++;
            }
 
            // Consider the case of
            // even length subarray
            straightScore = 0;
            reverseScore = 0;
 
            prev = mid - 1;
            next = mid;
            while (prev >= 0 && next < n) {
 
                // Update both the scores
                straightScore += (a[prev] * b[prev]
                                  + a[next] * b[next]);
                reverseScore += (a[prev] * b[next]
                                 + a[next] * b[prev]);
 
                res = Math.max(res, Math.max(straightScore,
                                             reverseScore));
 
                prev--;
                next++;
            }
        }
 
        // Print the result
        System.out.println(res);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int A[] = { 13, 4, 5 };
        int B[] = { 10, 22, 2 };
        int N = A.length;
        maxScoreSubArray(A, B, N);
    }
}
 
        // This code is contributed by Potta Lokesh


Python3
# Python3 program for the above approach
 
# Function to calculate the score
# of same-indexed subarrays selected
# from the arrays a[] and b[]
def maxScoreSubArray(a, b, n):
     
    # Store the required result
    res = 0
 
    # Iterate in the range [0, N-1]
    for mid in range(n):
         
        # Consider the case of odd
        # length subarray
        straightScore = a[mid] * b[mid]
        reverseScore = a[mid] * a[mid]
        prev = mid - 1
        next = mid + 1
 
        # Update the maximum score
        res = max(res, max(straightScore,
                           reverseScore))
 
        # Expanding the subarray in both
        # directions with equal length
        # so that mid poremains same
        while (prev >= 0 and next < n):
 
            # Update both the scores
            straightScore += (a[prev] * b[prev] +
                              a[next] * b[next])
            reverseScore += (a[prev] * b[next] +
                             a[next] * b[prev])
 
            res = max(res, max(straightScore,
                               reverseScore))
 
            prev -= 1
            next += 1
 
        # Consider the case of
        # even length subarray
        straightScore = 0
        reverseScore = 0
 
        prev = mid - 1
        next = mid
         
        while (prev >= 0 and next < n):
 
            # Update both the scores
            straightScore += (a[prev] * b[prev] +
                              a[next] * b[next])
            reverseScore += (a[prev] * b[next] +
                             a[next] * b[prev])
 
            res = max(res, max(straightScore,
                               reverseScore))
 
            prev -= 1
            next += 1
 
    # Print the result
    print(res)
 
# Driver Code
if __name__ == '__main__':
     
    A = [ 13, 4, 5 ]
    B = [ 10, 22, 2 ]
    N = len(A)
     
    maxScoreSubArray(A, B, N)
 
# This code is contributed by mohit kumar 29


C#
// C# Program for the above approach
using System;
 
public class GFG{
     
    // Function to calculate the score
    // of same-indexed subarrays selected
    // from the arrays a[] and b[]
    static void maxScoreSubArray(int[] a, int[] b, int n)
    {
       
        // Store the required result
        int res = 0;
  
        // Iterate in the range [0, N-1]
        for (int mid = 0; mid < n; mid++) {
  
            // Consider the case of odd
            // length subarray
            int straightScore = a[mid] * b[mid],
                reverseScore = a[mid] * a[mid];
            int prev = mid - 1, next = mid + 1;
  
            // Update the maximum score
            res = Math.Max(
                res, Math.Max(straightScore, reverseScore));
  
            // Expanding the subarray in both
            // directions with equal length
            // so that mid point remains same
            while (prev >= 0 && next < n) {
  
                // Update both the scores
                straightScore += (a[prev] * b[prev]
                                  + a[next] * b[next]);
                reverseScore += (a[prev] * b[next]
                                 + a[next] * b[prev]);
  
                res = Math.Max(res, Math.Max(straightScore,
                                             reverseScore));
  
                prev--;
                next++;
            }
  
            // Consider the case of
            // even length subarray
            straightScore = 0;
            reverseScore = 0;
  
            prev = mid - 1;
            next = mid;
            while (prev >= 0 && next < n) {
  
                // Update both the scores
                straightScore += (a[prev] * b[prev]
                                  + a[next] * b[next]);
                reverseScore += (a[prev] * b[next]
                                 + a[next] * b[prev]);
  
                res = Math.Max(res, Math.Max(straightScore,
                                             reverseScore));
  
                prev--;
                next++;
            }
        }
  
        // Print the result
        Console.WriteLine(res);
    }
  
    // Driver Code  
    static public void Main (){
         
        int[] A = { 13, 4, 5 };
        int[] B = { 10, 22, 2 };
        int N = A.Length;
        maxScoreSubArray(A, B, N);
         
    }
}
 
// This code is contributed by patel2127.


Javascript


输出:
326

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

高效方法:上述方法也可以通过将每个元素视为每个可能子数组的中点进行优化,然后在两个方向上扩展子数组,同时更新每个值的最大分数。请按照以下步骤解决问题:

  • 初始化一个变量,比如res来存储结果最大值。
  • 使用变量mid遍历范围[1, N – 1]并执行以下步骤:
    • 在奇数长度子数组的情况下,将两个变量(例如score1score2 )初始化为A[mid]*B[mid]
    • 初始化两个变量,例如prev(mid – 1)next(mid + 1)以扩展当前子数组。
    • 迭代一个循环,直到prev为正且next的值小于N并执行以下步骤:
      • (a[prev]*b[prev]+a[next]*b[next])的值添加到变量score1中。
      • (a[prev]*b[next]+a[next]*b[prev])的值添加到变量score2中。
      • res的值更新为score1score2res的最大值。
      • prev的值减1并将next的值增加1
    • score1score2的值更新为0 ,并将prev的值设置为(mid – 1) ,将next的值设置为mid ,以考虑偶数长度子数组的情况。
  • 完成上述步骤后,打印res的值作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to calculate the score
// of same-indexed subarrays selected
// from the arrays a[] and b[]
void maxScoreSubArray(int* a, int* b,
                      int n)
{
    // Store the required result
    int res = 0;
 
    // Iterate in the range [0, N-1]
    for (int mid = 0; mid < n; mid++) {
 
        // Consider the case of odd
        // length subarray
        int straightScore = a[mid] * b[mid],
            reverseScore = a[mid] * a[mid];
        int prev = mid - 1, next = mid + 1;
 
        // Update the maximum score
        res = max(res, max(straightScore,
                           reverseScore));
 
        // Expanding the subarray in both
        // directions with equal length
        // so that mid point remains same
        while (prev >= 0 && next < n) {
 
            // Update both the scores
            straightScore
                += (a[prev] * b[prev]
                    + a[next] * b[next]);
            reverseScore
                += (a[prev] * b[next]
                    + a[next] * b[prev]);
 
            res = max(res,
                      max(straightScore,
                          reverseScore));
 
            prev--;
            next++;
        }
 
        // Consider the case of
        // even length subarray
        straightScore = 0;
        reverseScore = 0;
 
        prev = mid - 1, next = mid;
        while (prev >= 0 && next < n) {
 
            // Update both the scores
            straightScore
                += (a[prev] * b[prev]
                    + a[next] * b[next]);
            reverseScore
                += (a[prev] * b[next]
                    + a[next] * b[prev]);
 
            res = max(res,
                      max(straightScore,
                          reverseScore));
 
            prev--;
            next++;
        }
    }
 
    // Print the result
    cout << res;
}
 
// Driver Code
int main()
{
    int A[] = { 13, 4, 5 };
    int B[] = { 10, 22, 2 };
    int N = sizeof(A) / sizeof(A[0]);
    maxScoreSubArray(A, B, N);
 
    return 0;
}

Java

// Java Program for the above approach
import java.io.*;
 
class GFG {
    // Function to calculate the score
    // of same-indexed subarrays selected
    // from the arrays a[] and b[]
    static void maxScoreSubArray(int[] a, int[] b, int n)
    {
        // Store the required result
        int res = 0;
 
        // Iterate in the range [0, N-1]
        for (int mid = 0; mid < n; mid++) {
 
            // Consider the case of odd
            // length subarray
            int straightScore = a[mid] * b[mid],
                reverseScore = a[mid] * a[mid];
            int prev = mid - 1, next = mid + 1;
 
            // Update the maximum score
            res = Math.max(
                res, Math.max(straightScore, reverseScore));
 
            // Expanding the subarray in both
            // directions with equal length
            // so that mid point remains same
            while (prev >= 0 && next < n) {
 
                // Update both the scores
                straightScore += (a[prev] * b[prev]
                                  + a[next] * b[next]);
                reverseScore += (a[prev] * b[next]
                                 + a[next] * b[prev]);
 
                res = Math.max(res, Math.max(straightScore,
                                             reverseScore));
 
                prev--;
                next++;
            }
 
            // Consider the case of
            // even length subarray
            straightScore = 0;
            reverseScore = 0;
 
            prev = mid - 1;
            next = mid;
            while (prev >= 0 && next < n) {
 
                // Update both the scores
                straightScore += (a[prev] * b[prev]
                                  + a[next] * b[next]);
                reverseScore += (a[prev] * b[next]
                                 + a[next] * b[prev]);
 
                res = Math.max(res, Math.max(straightScore,
                                             reverseScore));
 
                prev--;
                next++;
            }
        }
 
        // Print the result
        System.out.println(res);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int A[] = { 13, 4, 5 };
        int B[] = { 10, 22, 2 };
        int N = A.length;
        maxScoreSubArray(A, B, N);
    }
}
 
        // This code is contributed by Potta Lokesh

Python3

# Python3 program for the above approach
 
# Function to calculate the score
# of same-indexed subarrays selected
# from the arrays a[] and b[]
def maxScoreSubArray(a, b, n):
     
    # Store the required result
    res = 0
 
    # Iterate in the range [0, N-1]
    for mid in range(n):
         
        # Consider the case of odd
        # length subarray
        straightScore = a[mid] * b[mid]
        reverseScore = a[mid] * a[mid]
        prev = mid - 1
        next = mid + 1
 
        # Update the maximum score
        res = max(res, max(straightScore,
                           reverseScore))
 
        # Expanding the subarray in both
        # directions with equal length
        # so that mid poremains same
        while (prev >= 0 and next < n):
 
            # Update both the scores
            straightScore += (a[prev] * b[prev] +
                              a[next] * b[next])
            reverseScore += (a[prev] * b[next] +
                             a[next] * b[prev])
 
            res = max(res, max(straightScore,
                               reverseScore))
 
            prev -= 1
            next += 1
 
        # Consider the case of
        # even length subarray
        straightScore = 0
        reverseScore = 0
 
        prev = mid - 1
        next = mid
         
        while (prev >= 0 and next < n):
 
            # Update both the scores
            straightScore += (a[prev] * b[prev] +
                              a[next] * b[next])
            reverseScore += (a[prev] * b[next] +
                             a[next] * b[prev])
 
            res = max(res, max(straightScore,
                               reverseScore))
 
            prev -= 1
            next += 1
 
    # Print the result
    print(res)
 
# Driver Code
if __name__ == '__main__':
     
    A = [ 13, 4, 5 ]
    B = [ 10, 22, 2 ]
    N = len(A)
     
    maxScoreSubArray(A, B, N)
 
# This code is contributed by mohit kumar 29

C#

// C# Program for the above approach
using System;
 
public class GFG{
     
    // Function to calculate the score
    // of same-indexed subarrays selected
    // from the arrays a[] and b[]
    static void maxScoreSubArray(int[] a, int[] b, int n)
    {
       
        // Store the required result
        int res = 0;
  
        // Iterate in the range [0, N-1]
        for (int mid = 0; mid < n; mid++) {
  
            // Consider the case of odd
            // length subarray
            int straightScore = a[mid] * b[mid],
                reverseScore = a[mid] * a[mid];
            int prev = mid - 1, next = mid + 1;
  
            // Update the maximum score
            res = Math.Max(
                res, Math.Max(straightScore, reverseScore));
  
            // Expanding the subarray in both
            // directions with equal length
            // so that mid point remains same
            while (prev >= 0 && next < n) {
  
                // Update both the scores
                straightScore += (a[prev] * b[prev]
                                  + a[next] * b[next]);
                reverseScore += (a[prev] * b[next]
                                 + a[next] * b[prev]);
  
                res = Math.Max(res, Math.Max(straightScore,
                                             reverseScore));
  
                prev--;
                next++;
            }
  
            // Consider the case of
            // even length subarray
            straightScore = 0;
            reverseScore = 0;
  
            prev = mid - 1;
            next = mid;
            while (prev >= 0 && next < n) {
  
                // Update both the scores
                straightScore += (a[prev] * b[prev]
                                  + a[next] * b[next]);
                reverseScore += (a[prev] * b[next]
                                 + a[next] * b[prev]);
  
                res = Math.Max(res, Math.Max(straightScore,
                                             reverseScore));
  
                prev--;
                next++;
            }
        }
  
        // Print the result
        Console.WriteLine(res);
    }
  
    // Driver Code  
    static public void Main (){
         
        int[] A = { 13, 4, 5 };
        int[] B = { 10, 22, 2 };
        int N = A.Length;
        maxScoreSubArray(A, B, N);
         
    }
}
 
// This code is contributed by patel2127.

Javascript


输出:
326

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