Maximum Total Value of Covered Indices Problem
Description
LeetCode Problem 3952.
You are given an integer array nums of length n and a binary string s of length n, where s[i] == '1' means index i initially contains a token and s[i] == '0' means it does not.
You may perform the following operation any number of times:
- Choose a token currently located at index
i, wherei > 0, such that this token has not been moved before. - Move this token from index
ito indexi - 1.
An index is considered covered if it contains a token after all moves.
Return an integer denoting the maximum total value of nums at the covered indices after optimally performing the operations.
Example 1:
Input: nums = [9,2,6,1], s = "0101"
Output: 15
Explanation:
- Initially, indices 1 and 3 contain tokens.
- Move the token from index 3 to index 2.
- Move the token from index 1 to index 0.
- The covered indices are [0, 2], so the total value is nums[0] + nums[2] = 9 + 6 = 15.
Example 2:
Input: nums = [5,1,4], s = "001"
Output: 4
Explanation:
- Initially, only index 2 contains a token.
- It is optimal to leave the token at index 2.
- The covered index is [2], so the total value is nums[2] = 4.
Example 3:
Input: nums = [9,3,5], s = "011"
Output: 14
Explanation:
- Initially, indices 1 and 2 contain tokens.
- Move the token from index 1 to index 0.
- The covered indices are [0, 2], so the total value is nums[0] + nums[2] = 9 + 5 = 14.
Constraints:
1 <= n == nums.length == s.length <= 10^51 <= nums[i] <= 10^5s[i]is either'0'or'1'
Solution
Approach: Dynamic Programming
A token at index i can either stay at i or move to i - 1, and an index is only worth nums[i] once, however many tokens it holds. Scan left to right and keep two best totals after deciding the tokens at indices up to i: d1 when index i is covered by its own token staying, and d0 when it is not (yet).
Index i - 1 is finalized at step i: it is covered if the token at i - 1 stayed, or if a token at i moves left onto it. For a token at i we may stay (go to d1) or move (go to d0 and always collect nums[i - 1]); with no token, we go to d0. At the end, index n - 1 counts only when its own token stayed.
Complexity: time O(n), space O(1).
class Solution:
def maxTotal(self, nums: List[int], s: str) -> int:
n = len(nums)
NEG = float("-inf")
# d1: index i holds the token that started there; d0: it does not
d0, d1 = (NEG, 0) if s[0] == "1" else (0, NEG)
for i in range(1, n):
n0 = n1 = NEG
for p, base in ((0, d0), (1, d1)):
if base == NEG:
continue
gain = nums[i - 1] if p else 0
if s[i] == "1":
n1 = max(n1, base + gain)
n0 = max(n0, base + nums[i - 1])
else:
n0 = max(n0, base + gain)
d0, d1 = n0, n1
return int(max(d0, d1 + nums[n - 1]))