1537. Get the Maximum Score

You are given two sorted arrays of distinct integers nums1 and nums2.

valid path is defined as follows:

  • Choose array nums1 or nums2 to traverse (from index-0).
  • Traverse the current array from left to right.
  • If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).

The score is defined as the sum of uniques values in a valid path.

Return the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7.

Example 1:

Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
Output: 30
Explanation: Valid paths:
[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10],  (starting from nums1)
[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10]    (starting from nums2)
The maximum is obtained with the path in green [2,4,6,8,10].

Example 2:

Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100]
Output: 109
Explanation: Maximum sum is obtained with the path [1,3,5,100].

Example 3:

Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]
Output: 40
Explanation: There are no common elements between nums1 and nums2.
Maximum sum is obtained with the path [6,7,8,9,10].

Constraints:

  • 1 <= nums1.length, nums2.length <= 105
  • 1 <= nums1[i], nums2[i] <= 107
  • nums1 and nums2 are strictly increasing.

题目:给定两个数组,从前往后遍历,在数组值相等时可以交换数组遍历。遍历过的值相加,问最后最大值路径;

思路:直接找两个数组每相邻两个相等值之间的和。结果加上最大和即可。数组是严格递增的,因此不存在相等的情况,使得题目简单多了。

代码:

class Solution {
public:
    int maxSum(vector<int>& nums1, vector<int>& nums2) {
        long res = 0;
        int i1 = 0, i2 = 0, mod = 1000000007;
        while(i1 < nums1.size() || i2 < nums2.size()){
            long sum1 = 0, sum2 = 0;
            while(i1 < nums1.size() && i2 < nums2.size() && nums1[i1] != nums2[i2]){
                if(nums1[i1] < nums2[i2]) sum1 += nums1[i1++];
                else sum2 += nums2[i2++];
            }
            if(i1 == nums1.size()){
                while(i2 < nums2.size()) sum2 += nums2[i2++];
            } else if(i2 == nums2.size()){
                while(i1 < nums1.size()) sum1 += nums1[i1++];
            } else {
                sum2 += nums2[i2++];
                sum1 += nums1[i1++];
            }
            res = (res + max(sum1, sum2)) % mod;
        }
        return res;
    }
};

time: O(N), space:O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值