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).

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 10^9 + 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].

思路:就是一个merge sort的变种,我contest的时候,老想着dp,其实不用,用个变量记录当前每条线的current sum就可以,遇见相等 的,取最大值,然后归零,继续走。当前走过的最大,已经记录在res里面,相当于从新开始走;

class Solution {
    public int maxSum(int[] A, int[] B) {
        int n = A.length;
        int m = B.length;
        int MOD = 1000000007;
        
        long res = 0;
        long sum1 = 0;
        long sum2 = 0;
        int i = 0; int j = 0;
        while(i < n && j < m) {
            if(A[i] == B[j]) {
                res = (res + Math.max(sum1, sum2) + A[i]) % MOD;
                sum1 = 0;
                sum2 = 0;
                i++;
                j++;
            } else if(A[i] < B[j]) {
                sum1 = (sum1 + A[i++]) % MOD;
            } else {
                sum2 = (sum2 + B[j++]) % MOD;
            }
        }
        
        while(i < n) {
            sum1 = (sum1 + A[i++]);
        }
        
        while(j < m) {
            sum2 = (sum2 + B[j++]);
        }
        
        res = (res + Math.max(sum1, sum2)) % MOD;
        
        return (int) res;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值