KatInterview

Sentinels on a Road: Best Covered Value With Single Left Steps

Greedy & IntervalsAuto-graded · 19 test cases
MediumAuto-gradedGreedy & Intervalsgreedystringsarrays

Last updated

Maximize the total value of covered towns on a line when each sentinel may step one town left at most once into an empty town, by finding which town each run of sentinels leaves uncovered.

Sentinels on a Road

A road has n towns in a row, numbered from left to right starting at 1. You are given:

  • values: a list of n non-negative integers, where values[i] is the value of town i + 1.
  • guards: a string of length n made of '0' and '1'. If guards[i] == '1', a sentinel starts in town i + 1. If it is '0', that town starts empty.

Each town holds at most one sentinel at any moment.

Moves

Each sentinel may take at most one step in total. A step moves a sentinel from its town to the town immediately to its left. The step is allowed only if:

  • the sentinel is not in the leftmost town, and
  • the town to its left holds no sentinel at that moment.

Steps happen one at a time, and you choose the order. A town that was vacated earlier can therefore receive a sentinel later. A sentinel that has already stepped cannot step again.

Goal

After you finish moving, the covered value is the sum of values over all towns that contain a sentinel. Return the largest covered value you can reach. You may also choose to make no moves at all.

Constraints

  • 1 <= n <= 10^5
  • len(values) == len(guards) == n
  • 0 <= values[i] <= 10^9
  • guards contains only the characters '0' and '1'
  • The answer may exceed 32-bit range.

Examples

Example 1

Input: max_covered_value([10, 5, 8, 9, 6], '01101')

Output: 27

Hints

Hint 1

Sentinels only move left, and only by one town. Ask which sentinels can ever influence each other.

Hint 2

Look at a maximal block of consecutive '1's with an empty town directly to its left. If the block has k sentinels, they end up in k of the k+1 towns formed by the block plus that empty town. Which towns can be the one left uncovered?

Hint 3

Any town in that group can be the uncovered one if you shift sentinels left-to-right up to it. So each block with an empty left neighbor gains the left neighbor's value minus the cheapest town in the block, if that is positive. Blocks at the very start cannot move.