Monday, August 31, 2020

LeetCode [1425] Constrained Subsequence Sum

 1425. Constrained Subsequence Sum

Hard

Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.

subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.

 

Example 1:

Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].

Example 2:

Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.

Example 3:

Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].

 

Constraints:

  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public int constrainedSubsetSum(int[] nums, int k) {
        Deque<Integer> dq = new ArrayDeque<>();
        int n = nums.length, r = 0, ret = Integer.MIN_VALUE;
        int[] dp = new int[n];
        while(r<n){
            dp[r] = nums[r];
            if(r-k-1>=0 && !dq.isEmpty() && dq.peek()==dp[r-k-1]){
                dq.poll();
            }
            if(!dq.isEmpty() && dq.peek()>0){
                dp[r] += dq.peek();
            }
            while(!dq.isEmpty() && dp[r]>dq.peekLast()){
                dq.pollLast();
            }
            dq.add(dp[r]);
            ret = Math.max(ret, dp[r++]);
        }
        return ret;
    }
}

No comments:

Post a Comment