Skip to content

Commit 3a92f5f

Browse files
authored
Create 1537-get-the-maximum-score.js
1 parent e470b1c commit 3a92f5f

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

1537-get-the-maximum-score.js

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
3+
You are given two sorted arrays of distinct integers nums1 and nums2.
4+
5+
A valid path is defined as follows:
6+
7+
Choose array nums1 or nums2 to traverse (from index-0).
8+
Traverse the current array from left to right.
9+
If you are reading any value that is present in nums1 and nums2 you are
10+
allowed to change your path to the other array.
11+
(Only one repeated value is considered in the valid path).
12+
Score is defined as the sum of uniques values in a valid path.
13+
14+
Return the maximum score you can obtain of all possible valid paths.
15+
16+
Since the answer may be too large, return it modulo 10^9 + 7.
17+
18+
Example 1:
19+
20+
Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
21+
Output: 30
22+
Explanation: Valid paths:
23+
[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)
24+
[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)
25+
The maximum is obtained with the path in green [2,4,6,8,10].
26+
27+
Example 2:
28+
29+
Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100]
30+
Output: 109
31+
Explanation: Maximum sum is obtained with the path [1,3,5,100].
32+
Example 3:
33+
34+
Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]
35+
Output: 40
36+
Explanation: There are no common elements between nums1 and nums2.
37+
Maximum sum is obtained with the path [6,7,8,9,10].
38+
Example 4:
39+
40+
Input: nums1 = [1,4,5,8,9,11,19], nums2 = [2,3,4,11,12]
41+
Output: 61
42+
43+
44+
Constraints:
45+
46+
1 <= nums1.length <= 10^5
47+
1 <= nums2.length <= 10^5
48+
1 <= nums1[i], nums2[i] <= 10^7
49+
nums1 and nums2 are strictly increasing.
50+
51+
*/
52+
53+
/**
54+
* @param {number[]} nums1
55+
* @param {number[]} nums2
56+
* @return {number}
57+
*/
58+
const maxSum = function(nums1, nums2) {
59+
let i = 0, j = 0, n = nums1.length, m = nums2.length;
60+
let a = 0, b = 0, mod = 10 ** 9 + 7;
61+
while (i < n || j < m) {
62+
if (i < n && (j === m || nums1[i] < nums2[j])) {
63+
a += nums1[i++];
64+
} else if (j < m && (i === n || nums1[i] > nums2[j])) {
65+
b += nums2[j++];
66+
} else {
67+
a = b = Math.max(a, b) + nums1[i];
68+
i++; j++;
69+
}
70+
}
71+
return Math.max(a, b) % mod;
72+
};

0 commit comments

Comments
 (0)