Maximize score of same-indexed subarrays selected from two given arrays
Last Updated :
23 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem