Maximize the sum

You are given two sorted arrays of distinct integers, ‘ARR1’ and ‘ARR2’. If you find a common element in both arrays, you can switch from one array to another.

Your task is to find a path through the intersections i.e common integers of ‘ARR1’ and ‘ARR2’, that produces maximum sum and return that maximum sum as the answer.

For example:
Let ‘ARR1’ = [1, 5, 10, 15, 20]  and ‘ARR2’ = [2, 4, 5, 9, 15]
In this example, common points are 5, 15.

First, we start with ARR2 and take the sum till 5 (i.e. sum = 11). Then we will switch to ‘ARR1’ at element 10 and take the sum till 15. So sum = 36. Now no element is left in ‘ARR2’ after 15, so we will continue in array 1. Hence sum is 56. And the path is 2 -> 4 -> 5 -> 10 -> 15 -> 20.

array

Input Format:
The first line of input contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first line of each test case contains two space-separated integers, ‘N’ and ‘M,’ representing the number of elements in ‘ARR1’ and ‘ARR2’.

The second line of each test case contains ‘N’ single space-separated integers denoting the values of ‘ARR1’.

The third line of each test case contains ‘M’ single space-separated integers denoting the values of ‘ARR2’.
Output Format :
For each test case, print the maximum sum value.

Print the output of each test case in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= ‘T’ <= 100
1 <= ‘N’, ’M’ <= 10^4
1 <= ‘ARR1[i]’, ‘ARR2[j]’ <= 10^5

Time Limit: 1 second
CodingNinjas
author
2y
Recursive

In this problem, our primary focus is on the common elements i.e. an element that is present in both the arrays. Then, we have to decide whether we have to make a switch. So for that, first w...read more

CodingNinjas
author
2y
Memoization

In our previous approach, we use a recursive solution for solving this problem. But there are a lot of repetitive calculations in our previous approach. Let's assume a case in which both th...read more

CodingNinjas
author
2y
Two Pointer Approach

In this problem, our primary focus is on the common elements, i.e., elements present in both the arrays. Then, we have to decide whether we have to make a switch. So for that, we t...read more

Add answer anonymously...
Zomato Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter