Skip to content
Related Articles

Related Articles

Improve Article

Maximize score of same-indexed subarrays selected from two given arrays

  • Difficulty Level : Medium
  • Last Updated : 07 Jul, 2021

Given two arrays A[] and B[], both consisting of N positive integers, the task is to find the maximum score among all possible same-indexed subarrays in both the arrays such that the score of any subarray over the range [L, R] is calculated by the maximum of the values (AL*BL + AL + 1*BL + 1 + … + AR*BR) + (AR*BL + AR – 1*BL + 1 + … + AL*BR).

Examples:

Input: A[] = {13, 4, 5}, B[] = {10, 22, 2}
Output: 326
Explanation:
Consider the subarrays {A[0], A[1]} and {B[0], B[1]}. Score of these subarrays can be calculated as the maximum of the following two expressions:

  1. The value of the expression (A0*B0 + A1*B1) = 13 * 1 + 4 * 22 = 218.
  2. The value of the expression (A0*B1 + A1*B0) = 13 * 1 + 4 * 22 = 326.

Therefore, the maximum value from the above two expressions is 326, which is the maximum score among all possible subarrays.

Input: A[] = {9, 8, 7, 6, 1}, B[]={6, 7, 8, 9, 1}
Output: 230



Naive Approach: The simplest approach to solve the given problem is to generate all possible corresponding subarray and store all the scores of all subarray generated using the given criteria. After storing all the scores, print the maximum value among all the scores generated.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
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

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




<script>
 
// JavaScript program for the above approach
 
// Function to calculate the score
// of same-indexed subarrays selected
// from the arrays a[] and b[]
function currSubArrayScore(a, b, l, r)
{
    let straightScore = 0;
    let reverseScore = 0;
 
    // Traverse the current subarray
    for (let 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
function maxScoreSubArray(a, b, n) {
    // Stores the maximum score and the
    // starting and the ending point
    // of subarray with maximum score
    let res = 0, start = 0, end = 0;
 
    // Traverse all the subarrays
    for (let i = 0; i < n; i++) {
        for (let j = i; j < n; j++) {
 
            // Store the score of the
            // current subarray
            let currScore
                = currSubArrayScore(
                    a, b, i, j);
 
            // Update the maximum score
            if (currScore > res) {
                res = currScore;
                start = i;
                end = j;
            }
        }
    }
 
    // Print the maximum score
    document.write(res);
}
 
// Driver Code
 
let A = [13, 4, 5];
let B = [10, 22, 2];
let N = A.length;
maxScoreSubArray(A, B, N);
 
// This code is contributed by gfgking.
 
</script>
Output: 
326

 

Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by considering every element as the middle point of every possible subarray and then expand the subarray in both directions while updating the maximum score for every value. Follow the steps below to solve the problem:

  • Initialize a variable, say res to store the resultant maximum value.
  • Iterate over the range [1, N – 1] using the variable mid and perform the following steps:
    • Initialize two variables, say score1 and score2 as A[mid]*B[mid] in case of odd length subarray.
    • Initialize two variables, say prev as (mid – 1) and next as (mid + 1) to expand the current subarray.
    • Iterate a loop until prev is positive and the value of next is less than N and perform the following steps:
      • Add the value of (a[prev]*b[prev]+a[next]*b[next]) to the variable score1.
      • Add the value of (a[prev]*b[next]+a[next]*b[prev]) to the variable score2.
      • Update the value of res to the maximum of score1, score2, and res.
      • Decrement the value of prev by 1 and increment the value of next by 1.
    • Update the value of score1 and score2 as 0 and set the value of prev as (mid – 1) and next as mid to consider the case of even length subarray.
  • After completing the above steps, print the value of res as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
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




<script>
 
// JavaScript program for the above approach
 
 
// Function to calculate the score
// of same-indexed subarrays selected
// from the arrays a[] and b[]
function maxScoreSubArray(a, b, n) {
    // Store the required result
    let res = 0;
 
    // Iterate in the range [0, N-1]
    for (let mid = 0; mid < n; mid++) {
 
        // Consider the case of odd
        // length subarray
        let straightScore = a[mid] * b[mid],
            reverseScore = a[mid] * a[mid];
        let 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
    document.write(res);
}
 
// Driver Code
 
let A = [13, 4, 5];
let B = [10, 22, 2];
let N = A.length
maxScoreSubArray(A, B, N);
 
</script>
Output: 
326

 

Time Complexity: O(N2)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :