Maximize score of same-indexed subarrays selected from two given arrays
Last Updated :
09 Nov, 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:
- The value of the expression (A0*B0 + A1*B1) = 13 * 1 + 4 * 22 = 218.
- 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
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
<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>
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>
Time Complexity: O(N2)
Auxiliary Space: O(1)
Similar Reads
Rearrange two given arrays to maximize sum of same indexed elements
Given two arrays A[] and B[] of size N, the task is to find the maximum possible sum of abs(A[i] â B[i]) by rearranging the array elements. Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 2, 3, 4, 5}Output: 12Explanation: One of the possible rearrangements of A[] is {5, 4, 3, 2, 1}. One of the pos
5 min read
Maximum length of same indexed subarrays from two given arrays satisfying the given condition
Given two arrays arr[] and brr[] and an integer C, the task is to find the maximum possible length, say K, of the same indexed subarrays such that the sum of the maximum element in the K-length subarray in brr[] with the product between K and sum of the K-length subarray in arr[] does not exceed C.
15+ min read
Maximize sum of product of same-indexed elements of equal length subarrays obtained from two given arrays
Given two arrays arr[] and brr[] of size N and M integers respectively, the task is to maximize the sum of the product of the same-indexed elements of two subarrays of an equal length with the selected subarray from the array brr[] being reversed. Examples: Input: arr[] = {-1, 3, -2, 4, 5}, brr[] =
13 min read
Rearrange Array to maximize sum of MEX of all Subarrays starting from first index
Given an array arr[] of N elements ranging from 0 to N-1(both included), the task is to rearrange the array such that the sum of all the MEX from every subarray starting from index 0 is maximum. Duplicates can be present in the array. MEX of an array is the first non-negative element that is missing
8 min read
Maximize sum of selected integers from an Array of pair of integers as per given condition
Given an array arr[] having N pair of integers of the form (x, y), the task is to maximize the sum y values in selected pairs such that if a pair (xi, yi) is selected, the next xi pairs cannot be selected. Examples: Input: arr[]= {{1, 5}, {2, 7}, {1, 4}, {1, 5}, {1, 10}}Output: 19Explanation: Choose
15+ min read
Maximize sum of selected numbers from Array to empty it | Set 2
Given an array arr[] of N integers, the task is to maximize the sum of selected numbers over all the operations such that in each operation, choose a number Ai, delete one occurrence of it and delete all occurrences of Ai - 1 and Ai + 1 (if they exist) in the array until the array gets empty. Exampl
7 min read
Queries to count occurrences of maximum array element in subarrays starting from given indices
Given two arrays arr[] and q[] consisting of N integers, the task is for each query q[i] is to determine the number of times the maximum array element occurs in the subarray [q[i], arr[N - 1]]. Examples: Input: arr[] = {5, 4, 5, 3, 2}, q[] = {1, 2, 3, 4, 5}Output: 2 1 1 1 1Explanation:For the first
10 min read
Maximize sum of pairwise products generated from the given Arrays
Given three arrays arr1[], arr2[] and arr3[] of length N1, N2, and N3 respectively, the task is to find the maximum sum possible by adding the products of pairs taken from different arrays. Note: Each array element can be a part of a single pair. Examples: Input: arr1[] = {3, 5}, arr2[] = {2, 1}, ar
11 min read
Sum of subsets nearest to K possible from two given arrays
Given two arrays A[] and B[] consisting of N and M integers respectively, and an integer K, the task is to find the sum nearest to K possible by selecting exactly one element from the array A[] and an element from the array B[], at most twice. Examples: Input: A[] = {1, 7}, B[] = {3, 4}, K = 10Outpu
9 min read
Maximize sum by selecting X different-indexed elements from three given arrays
Given three arrays A[], B[] and C[] of size N and three positive integers X, Y, and Z, the task is to find the maximum sum possible by selecting at most N array elements such that at most X elements are from the array A[], at most Y elements from the array B[], at most Z elements are from the array
15+ min read