Highest Score from Alternating Back-and-Forth Board Moves

Hard · Coding & Algorithms · Software Engineer · HR Screen

Problem Statement

Given a 0-indexed integer array board of length n (whose entries may be negative, zero, or positive) and a step budget k, compute the highest score a marker can finish with under the following movement rules:

def max_row_walk_score(board: list[int], k: int) -> int:
  • Starting state: The marker begins at index 0 with total score 0 and may execute anywhere from 0 through k steps before halting. Halting immediately after 0 steps yields score 0.
  • Alternating directions: Numbering steps t = 1, 2, ..., every odd-numbered step (t = 1, 3, 5, ...) moves rightward from the current index p to any destination q satisfying p <= q <= n - 1, and every even-numbered step (t = 2, 4, 6, ...) moves leftward from p to any destination q satisfying 0 <= q <= p. Remaining in place (q == p) is legal on both odd and even steps and counts as that turn's move.
  • Scoring: A step between p and q adds the inclusive subarray sum board[min(p, q)] + ... + board[max(p, q)] to the running score. In particular, staying on p (q == p) adds board[p].
  • Non-negative balance rule: At the end of each step, the updated running score must be >= 0. Only the post-step total is checked (individual indices traversed mid-step are not checked one by one). Any step that would push the running score below 0 is illegal.

Return the maximum valid score obtainable within at most k steps.

Examples

Example 1

Input: board = [-1, 4, -2, 5], k = 3
Output: 20
  • Step 1 (right, 0 -> 3): adds -1 + 4 - 2 + 5 = 6, bringing the score to 6 at index 3.
  • Step 2 (left, 3 -> 1): adds 4 - 2 + 5 = 7, bringing the score to 13 at index 1.
  • Step 3 (right, 1 -> 3): adds 4 - 2 + 5 = 7 again, finishing with 20.

Example 2

Input: board = [2, -11, 7], k = 500000
Output: 3499981

Stepping directly from index 0 to index 2 on Step 1 would add 2 - 11 + 7 = -2, which violates the non-negative score requirement. Instead:

  • Step 1 (right, 0 -> 0) and Step 2 (left, 0 -> 0) stay on index 0, each adding 2 for a score of 4 (Step 2 must move leftward, so crossing to index 2 has to wait until Step 3).
  • Step 3 (right, 0 -> 2) adds 2 - 11 + 7 = -2, leaving score 4 - 2 = 2 on index 2.
  • All remaining 499,997 steps stay on index 2 (2 -> 2) and add 7 apiece, reaching 2 + 499,997 * 7 = 3,499,981.

Example 3

Input: board = [-6, 2, 3], k = 8
Output: 0

Every rightward choice from index 0 on Step 1 yields a negative sum (-6, -4, or -1), so no legal first step exists. Halting after 0 steps returns 0.

Constraints

  • 1 <= len(board) <= 50
  • -4 * 10^5 <= board[i] <= 4 * 10^5
  • 1 <= k <= 4 * 10^8
  • Results can reach 8 * 10^15, so 64-bit (or arbitrary-precision) integers are required.

Step-by-step walkthrough

  1. Restate the rules and spot the monotonicity shortcut

    We begin at index 0 with score 0 and perform up to k steps (k <= 4 * 10^8) across n signed board entries (n <= 50):

    • Odd steps (1, 3, 5, ...) travel right: from p to any q with p <= q <= n - 1.
    • Even steps (2, 4, 6, ...) travel left: from p to any q with 0 <= q <= p.
    • Each step adds the inclusive subarray sum from min(p, q) through max(p, q) — so remaining in place (q = p) still adds board[p].
    • At the conclusion of each complete step (not cell-by-cell mid-step), the running score must stay >= 0. Halting after any count of steps (0 steps gives 0) is allowed.
    Example 2:  board = [2, -11, 7],  k = 500,000
      Step 1 (right, 0 -> 0): +2              -> score = 2
      Step 2 (left,  0 -> 0): +2              -> score = 4   (saved enough to cross -11!)
      Step 3 (right, 0 -> 2): 2 - 11 + 7 = -2 -> score = 2   (now standing on index 2)
      Steps 4..500,000 (stay on index 2):     +7 each        -> 2 + 499,997 * 7 = 3,499,981
    

    One monotonicity fact simplifies the state space: standing on the same cell at the same step number, a larger score strictly dominates a smaller score. Any future step sequence that stays >= 0 starting from score s also stays >= 0 starting from s' > s, finishing s' - s points higher.

  2. Why move-by-move DP is too slow

    Using monotonicity, a direct dynamic programming baseline maintains best_on[p] = maximum score reachable at cell p after t steps:

    def brute_max_row_walk_score(board: list[int], k: int) -> int:
        n = len(board)
        best_on = [None] * n
        best_on[0] = 0
        answer = 0
        for t in range(1, k + 1):
            new_best = [None] * n
            for p in range(n):
                if best_on[p] is None:
                    continue
                ends = range(p, n) if t % 2 == 1 else range(0, p + 1)
                for q in ends:
                    score = best_on[p] + sum(board[min(p, q):max(p, q) + 1])
                    if score >= 0 and (new_best[q] is None or score > new_best[q]):
                        new_best[q] = score
            best_on = new_best
            for score in best_on:
                if score is not None and score > answer:
                    answer = score
        return answer
    

    Even with prefix sums, O(k * n^2) work times out completely when k = 4 * 10^8. On a board like [1, -400000, ..., -400000, 400000], the marker must camp at cell 0 earning +1 per step for nearly 19,000,000 steps before crossing! We need to leap over long saving phases in O(1) time with division instead of ticking one step at a time.

  3. Pair moves into two-move rounds using prefix sums

    Bundle consecutive steps into two-step rounds: a round from start_cell (u) to end_cell (v) consists of one odd rightward step u -> e followed by one even leftward step e -> v. For both halves to obey direction rules, the turning cell e must lie at or to the right of both endpoints (e >= max(u, v)):

    cells:  0 ... u ............ v ........ e ...... n-1
                  |------------------------>|          odd step (right): adds sum(u .. e)
                                 |<---------|          even step (left): adds sum(v .. e)
    

    With prefix sums prefix_sum[i] = board[0] + ... + board[i - 1], the sum over board[l .. r] is prefix_sum[r + 1] - prefix_sum[l]. For turning cell e:

    • right_move_gain = prefix_sum[e + 1] - prefix_sum[u]
    • left_move_gain = prefix_sum[e + 1] - prefix_sum[v]
    • hop_gain = right_move_gain + left_move_gain

    Notice that both right_move_gain and hop_gain increase whenever prefix_sum[e + 1] increases! Consequently, choosing e >= max(u, v) with the largest prefix_sum[e + 1] (stored in best_right_prefix[max(u, v)]) maximizes the round's score gain and minimizes the entry balance needed to survive the rightward half without going negative.

    In particular, a stationary loop based at cell u (u -> best e -> u) earns loop_gain[u] = 2 * (best_right_prefix[u] - prefix_sum[u]) per round.

    num_cells = len(board)
    
    # prefix_sum[i] = board[0] + ... + board[i - 1], e.g. [0, 2, -9, -2] for [2, -11, 7].
    # Any closed cell range [left .. right] has sum prefix_sum[right + 1] - prefix_sum[left].
    prefix_sum = [0] * (num_cells + 1)
    for i in range(num_cells):
        prefix_sum[i + 1] = prefix_sum[i] + board[i]
    
    # best_right_prefix[x] = max(prefix_sum[e + 1]) over all turning cells e >= x.
    # For any right move forced to end at or after x, picking that e maximizes the score gained.
    best_right_prefix = [0] * num_cells
    best_right_prefix[num_cells - 1] = prefix_sum[num_cells]
    for x in range(num_cells - 2, -1, -1):
        best_right_prefix[x] = max(prefix_sum[x + 1], best_right_prefix[x + 1])
    
    # loop_gain[u] = best score gained in 1 round (right to best e >= u, then left back to u).
    loop_gain = [0] * num_cells
    for u in range(num_cells):
        best_one_way = best_right_prefix[u] - prefix_sum[u]
        loop_gain[u] = 2 * best_one_way
    
    
    def compute_hop(
        prefix_sum: List[int],
        best_right_prefix: List[int],
        start_cell: int,
        end_cell: int,
    ) -> Tuple[int, int]:
        """Return (hop_gain, min_score_needed) for the best 2-move round start_cell -> turn -> end_cell."""
        # The turning cell e must be >= start_cell (right move) and >= end_cell (left move back).
        first_valid_turn = max(start_cell, end_cell)
        best_turn_prefix = best_right_prefix[first_valid_turn]
    
        right_move_gain = best_turn_prefix - prefix_sum[start_cell]
        left_move_gain = best_turn_prefix - prefix_sum[end_cell]
        hop_gain = right_move_gain + left_move_gain
    
        # Both after the right move AND after the full round, the score must stay >= 0.
        min_score_needed = max(0, -right_move_gain, -hop_gain)
        return hop_gain, min_score_needed
    
  4. Why an optimal walk only climbs to better loop cells

    Why relocate from cell u to another cell v instead of repeating u's best loop? Only to reach a cell with a strictly higher loop_gain — either to farm points there until step k, or as an intermediate stepping stone that accumulates cash faster toward an even richer cell later (such as cell 1 in [-1, 1, -9, 5]).

    Let's confirm why detours through weaker cells are never beneficial, using x <= y => best_right_prefix[x] >= best_right_prefix[y]:

    1. A hop u -> v never exceeds the average of looping at u and v: because best_right_prefix[max(u, v)] is at most both best_right_prefix[u] and best_right_prefix[v], hop_gain(u, v) <= (loop_gain[u] + loop_gain[v]) // 2.
    2. A two-round detour u -> w -> v never beats a direct hop u -> v plus one loop: both best_right_prefix[max(u, w)] and best_right_prefix[max(w, v)] are <= best_right_prefix[w], and their minimum equals best_right_prefix[max(u, v, w)] <= best_right_prefix[max(u, v)]. Summing them gives hop_gain(u, w) + hop_gain(w, v) <= hop_gain(u, v) + loop_gain[w].

    Whenever loop_gain[w] <= loop_gain[b] for some previously visited cell b, swapping u -> w -> v for one extra loop on b plus the direct hop u -> v spends the exact same number of rounds, keeps intermediate balances at least as high, and yields at least as large a final score!

    Optimal walk structure (at most n cells, strictly increasing loop_gain):
    
      cell 0  --(loop r0 times)--> hop -->  cell c1  --(loop r1 times)--> hop -->  cell cm (loop rest!)
      loop_gain[0]               <          loop_gain[c1]               <          loop_gain[cm]
    

    Because loop_gain strictly rises on every hop, no cell appears twice in the stepping-stone chain, capping chain length at n!

  5. Jump over saving phases with ceiling division

    Suppose we sit on cell u with current_score and plan to hop to a higher-rate cell v (loop_gain[v] > loop_gain[u]). How many loops should we run on u beforehand?

    Strictly the minimum count required to reach min_score_needed! Any extra loop performed on u beyond affordability could instead be performed on v after the hop, earning loop_gain[v] > loop_gain[u] in the same round budget.

    When current_score < min_score_needed and gain_per_loop > 0, closing deficit = min_score_needed - current_score takes ceil(deficit / gain_per_loop) loops, computed exactly with (deficit + gain_per_loop - 1) // gain_per_loop:

    def loops_needed_to_afford(
        current_score: int, min_score_needed: int, gain_per_loop: int
    ) -> Optional[int]:
        """Return the fewest loops at gain_per_loop needed to lift current_score to min_score_needed."""
        if current_score >= min_score_needed:
            return 0
        if gain_per_loop <= 0:
            return None
        deficit = min_score_needed - current_score
        # Ceiling division ceil(deficit / gain_per_loop) using exact integer arithmetic.
        return (deficit + gain_per_loop - 1) // gain_per_loop
    
  6. Prune dominated states and run DP in increasing loop order

    Distinct stepping-stone paths may land on the same cell v with different (rounds_used, score) pairs. If state A = (r1, s1) uses no more rounds than B = (r2, s2) (r1 <= r2), A can spend r2 - r1 loops at v (at rate loop_rate = max(loop_gain[v], 0)) to reach s1 + (r2 - r1) * loop_rate by round r2.

    Thus A dominates B whenever:

      s1 + (r2 - r1) * loop_rate >= s2
      <=>  s1 - r1 * loop_rate   >= s2 - r2 * loop_rate
    

    Sorting candidate states by rounds_used ascending (and higher score first on ties), we retain only states whose adjusted value score - rounds_used * loop_rate sets a strict new maximum. Processing target cells in ascending loop_gain order guarantees every valid source_cell frontier is finalized before target_cell:

    def sort_key_rounds_first(state: Tuple[int, int]) -> Tuple[int, int]:
        """Sort states by rounds_used ascending, breaking ties by highest score first."""
        rounds_used, score = state
        return (rounds_used, -score)
    
    
    def prune_dominated_states(
        states: List[Tuple[int, int]], loop_rate: int
    ) -> List[Tuple[int, int]]:
        """Keep only states that no earlier-round state can match or beat by looping at loop_rate."""
        states.sort(key=sort_key_rounds_first)
        kept: List[Tuple[int, int]] = []
        best_adjusted_score: Optional[int] = None
    
        for rounds_used, score in states:
            # Comparing s1 + (r2 - r1) * loop_rate >= s2 rearranges to (s1 - r1 * loop_rate) >= (s2 - r2 * loop_rate).
            adjusted_score = score - rounds_used * loop_rate
            if best_adjusted_score is None or adjusted_score > best_adjusted_score:
                kept.append((rounds_used, score))
                best_adjusted_score = adjusted_score
        return kept
    
  7. Spend remaining rounds and walk through Example 2

    After computing frontier[cell] for every cell, each kept state (rounds_used, current_score) is evaluated as a candidate ending cell:

    • When loop_gain[cell] > 0, spend all rounds_allowed - rounds_used remaining two-step rounds looping on cell.
    • When k is odd (k % 2 == 1), one final rightward step remains; from cell, its best gain is best_right_prefix[cell] - prefix_sum[cell] == loop_gain[cell] // 2.
    • When loop_gain[cell] <= 0, stop immediately because additional steps from cell cannot raise the score.

    Let's trace Example 2 (board = [2, -11, 7], k = 500,000, rounds_allowed = 250,000):

    Precomputation:
      prefix_sum        = [0, 2, -9, -2]
      best_right_prefix = [2, -2, -2]
      loop_gain         = [4, -8, 14]   (cell 0 earns +4/round; cell 2 earns +14/round)
    
    DP in loop_gain order (cell 1 -> cell 0 -> cell 2):
      - cell 1 (loop -8): below cell 0's rate (4), so frontier[1] = []
      - cell 0 (loop  4): initial state frontier[0] = [(0, 0)]
      - cell 2 (loop 14): hop from cell 0 turns at e = 2 (best_turn_prefix = -2):
          right_move_gain  = -2 - 0    = -2   (step 0 -> 2 adds 2 - 11 + 7 = -2)
          left_move_gain   = -2 - (-9) = +7   (step 2 -> 2 adds 7)
          hop_gain         = -2 + 7    = +5
          min_score_needed = max(0, 2, -5) = 2
          extra_loops at cell 0 = ceil((2 - 0) / 4) = 1 loop (gains +4)
          total_rounds = 0 + 1 + 1 = 2,  arrival_score = 0 + 4 + 5 = 9
          frontier[2] = [(2, 9)]
    
    Finish:
      - End on cell 0: 0 + 250,000 * 4           = 1,000,000
      - End on cell 2: 9 + (250,000 - 2) * 14    = 3,499,981  <-- maximum!
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def max_row_walk_score(board: list[int], k: int) -> int:
        num_cells = len(board)
    
        # prefix_sum[i] = board[0] + ... + board[i - 1], e.g. [0, 2, -9, -2] for [2, -11, 7].
        # Any closed cell range [left .. right] has sum prefix_sum[right + 1] - prefix_sum[left].
        prefix_sum = [0] * (num_cells + 1)
        for i in range(num_cells):
            prefix_sum[i + 1] = prefix_sum[i] + board[i]
    
        # best_right_prefix[x] = max(prefix_sum[e + 1]) over all turning cells e >= x.
        # For any right move forced to end at or after x, picking that e maximizes the score gained.
        best_right_prefix = [0] * num_cells
        best_right_prefix[num_cells - 1] = prefix_sum[num_cells]
        for x in range(num_cells - 2, -1, -1):
            best_right_prefix[x] = max(prefix_sum[x + 1], best_right_prefix[x + 1])
    
        # loop_gain[u] = best score gained in 1 round (right to best e >= u, then left back to u).
        loop_gain = [0] * num_cells
        for u in range(num_cells):
            best_one_way = best_right_prefix[u] - prefix_sum[u]
            loop_gain[u] = 2 * best_one_way
    
        # One full round consists of 1 odd (right) move + 1 even (left) move.
        rounds_allowed = k // 2
    
        # frontier[v]: list of Pareto-optimal (rounds_used, score) pairs standing on cell v
        # right before an odd move, where v has the strictly highest loop_gain visited so far.
        frontier: List[List[Tuple[int, int]]] = []
        for _ in range(num_cells):
            frontier.append([])
        frontier[0] = [(0, 0)]
    
        # Process cells in increasing loop_gain order so every valid stepping-stone u is ready before v.
        cells_by_loop = []
        for cell in range(num_cells):
            cells_by_loop.append((loop_gain[cell], cell))
        cells_by_loop.sort()
    
        for _, target_cell in cells_by_loop:
            # We already start on cell 0 at round 0 with score 0; never hop back to cell 0 later.
            if target_cell == 0:
                continue
    
            candidates = []
            for source_cell in range(num_cells):
                # Chains only climb to cells with a strictly better loop_gain.
                if loop_gain[source_cell] >= loop_gain[target_cell] or not frontier[source_cell]:
                    continue
    
                hop_gain, min_score_needed = compute_hop(
                    prefix_sum, best_right_prefix, source_cell, target_cell
                )
                for rounds_used, current_score in frontier[source_cell]:
                    extra_loops = loops_needed_to_afford(
                        current_score, min_score_needed, loop_gain[source_cell]
                    )
                    if extra_loops is None:
                        continue
    
                    total_rounds = rounds_used + extra_loops + 1
                    if total_rounds <= rounds_allowed:
                        arrival_score = current_score + extra_loops * loop_gain[source_cell] + hop_gain
                        candidates.append((total_rounds, arrival_score))
    
            frontier[target_cell] = prune_dominated_states(candidates, max(loop_gain[target_cell], 0))
    
        # Phase 2: Try ending the walk on each cell v by spending remaining moves on v's best loop.
        best_score = 0
        for cell in range(num_cells):
            for rounds_used, current_score in frontier[cell]:
                final_score = current_score
                if loop_gain[cell] > 0:
                    remaining_rounds = rounds_allowed - rounds_used
                    final_score += remaining_rounds * loop_gain[cell]
                    # When k is odd, 1 right move remains at the end, adding best_one_way = loop_gain[cell] // 2.
                    if k % 2 == 1:
                        final_score += loop_gain[cell] // 2
                best_score = max(best_score, final_score)
    
        return best_score
    
    
    def compute_hop(
        prefix_sum: List[int],
        best_right_prefix: List[int],
        start_cell: int,
        end_cell: int,
    ) -> Tuple[int, int]:
        """Return (hop_gain, min_score_needed) for the best 2-move round start_cell -> turn -> end_cell."""
        # The turning cell e must be >= start_cell (right move) and >= end_cell (left move back).
        first_valid_turn = max(start_cell, end_cell)
        best_turn_prefix = best_right_prefix[first_valid_turn]
    
        right_move_gain = best_turn_prefix - prefix_sum[start_cell]
        left_move_gain = best_turn_prefix - prefix_sum[end_cell]
        hop_gain = right_move_gain + left_move_gain
    
        # Both after the right move AND after the full round, the score must stay >= 0.
        min_score_needed = max(0, -right_move_gain, -hop_gain)
        return hop_gain, min_score_needed
    
    
    def loops_needed_to_afford(
        current_score: int, min_score_needed: int, gain_per_loop: int
    ) -> Optional[int]:
        """Return the fewest loops at gain_per_loop needed to lift current_score to min_score_needed."""
        if current_score >= min_score_needed:
            return 0
        if gain_per_loop <= 0:
            return None
        deficit = min_score_needed - current_score
        # Ceiling division ceil(deficit / gain_per_loop) using exact integer arithmetic.
        return (deficit + gain_per_loop - 1) // gain_per_loop
    
    
    def sort_key_rounds_first(state: Tuple[int, int]) -> Tuple[int, int]:
        """Sort states by rounds_used ascending, breaking ties by highest score first."""
        rounds_used, score = state
        return (rounds_used, -score)
    
    
    def prune_dominated_states(
        states: List[Tuple[int, int]], loop_rate: int
    ) -> List[Tuple[int, int]]:
        """Keep only states that no earlier-round state can match or beat by looping at loop_rate."""
        states.sort(key=sort_key_rounds_first)
        kept: List[Tuple[int, int]] = []
        best_adjusted_score: Optional[int] = None
    
        for rounds_used, score in states:
            # Comparing s1 + (r2 - r1) * loop_rate >= s2 rearranges to (s1 - r1 * loop_rate) >= (s2 - r2 * loop_rate).
            adjusted_score = score - rounds_used * loop_rate
            if best_adjusted_score is None or adjusted_score > best_adjusted_score:
                kept.append((rounds_used, score))
                best_adjusted_score = adjusted_score
        return kept
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture the board cells as side gigs spaced along a road with toll plazas (negative entries) between them. You begin at index 0 with 0 coins, and your balance is forbidden from dipping below 0 at the end of any step. On board = [2, -11, 7], index 0 pays 2 coins per step while index 2 pays 7 coins behind an 11-coin toll: the winning plan is to repeat just enough shifts at index 0 to cover the crossing cost, jump across to index 2 once, and spend every remaining step farming 7 coins!

Why do standard shortcuts break down? Simulating steps one by one costs O(k * n^2) time, which stalls when k = 400,000,000. Even max-plus matrix exponentiation (squaring fixed transition tables in O(n^3 log k) time) fails because matrix squaring cannot enforce the score >= 0 floor across a saving phase lasting almost 20 million steps. Instead, we group each odd rightward step and even leftward step into a two-step round, prove that an optimal walk only ever relocates to cells with strictly higher per-round yield (loop_gain), and skip entire saving phases in O(1) time via ceiling division (rounding a quotient up to the next integer).

Let's trace board = [2, -11, 7] for k = 6 (3 two-step rounds) using prefix sums (a cumulative sum array where any closed range sum is a single subtraction) and suffix maximums (an array recording the highest prefix value at or to the right of each cell):

board:              [ 2, -11,  7]
prefix_sum:      [0,  2,  -9, -2]
best_right_prefix:   [2,  -2, -2]   (largest prefix_sum[e + 1] for e >= x)
loop_gain:           [4,  -8, 14]   (cell 0 earns +4/round; cell 2 earns +14/round)

Round 1: loop on cell 0 (0 -> 0 -> 0)         -> +2 + 2 = +4   (score = 4, enough to cross!)
Round 2: hop cell 0 -> turn at 2 -> cell 2    -> -2 + 7 = +5   (right half leaves 4 - 2 = 2 >= 0; score = 9)
Round 3: loop on cell 2 (2 -> 2 -> 2)         -> +7 + 7 = +14  (score = 23)

For k = 500,000 (250,000 rounds), Round 3 repeats 249,998 times via one multiplication: 9 + 249,998 * 14 = 3,499,981.

Complexity

Let n be len(board) (n <= 50).

  • Time: O(n^3 log n), completely independent of k. Computing prefix_sum, best_right_prefix, and loop_gain takes O(n) time. Each cell maintains a Pareto frontier (a filtered list of (rounds_used, score) states in which no kept entry can be matched or beaten by an earlier-round entry looping in place). Every kept state on cell v with loop_gain[v] > 0 exceeds the prior kept state's score by more than loop_gain[v], while arrival scores after at most n - 1 hops stay under n * loop_gain[v], bounding frontier[v] to at most n states (<= n - 1 when loop_gain[v] <= 0). Across n target cells we inspect up to n source cells and their O(n) states — producing O(n^2) candidates — and sort them in O(n^2 log n) time, for O(n^3 log n) total (~125,000 operations at n = 50).
  • Space: O(n^2). Storing n frontiers of at most n (rounds_used, score) pairs each plus three length-n arrays uses O(n^2) memory.

Edge cases

  • Single cell (n = 1): Every step is a zero-distance step on index 0 adding board[0], returning k * board[0] if board[0] > 0 and 0 otherwise.
  • All initial moves negative (Example 3, [-6, 2, 3]): Every prefix sum starting at index 0 is negative, so loop_gain[0] < 0, no hop is reachable from (0, 0), and best_score = 0 (halting at 0 steps).
  • k = 1: rounds_allowed = 0, so zero full rounds run; the odd-k branch adds loop_gain[0] // 2 = best_right_prefix[0] when positive, matching the best prefix sum from index 0.
  • Odd k (k % 2 == 1): After spending rounds_allowed - rounds_used full rounds on the final cell v, one rightward step remains and contributes loop_gain[v] // 2 whenever loop_gain[v] > 0.
  • Multi-hop stepping stones ([-1, 1, -9, 5]): Index 0 has loop_gain[0] = 0 and cannot save up for index 3 directly, so it hops to index 1 (loop_gain[1] = 2), farms points there, and then hops to index 3 (loop_gain[3] = 10).
  • Large outputs (8 * 10^15): 50 cells of 4 * 10^5 across 4 * 10^8 steps produce 8 * 10^15. Python handles big integers natively; in C++, Java, or Rust, use 64-bit signed integers (long long / i64).

Common mistakes

  • Simulating step-by-step or waiting for DP states to stabilize: On [1, -400000, ..., -400000, 400000], the marker must camp on index 0 for nearly 19 million steps before crossing, so only ceiling division runs in time.
  • Checking score >= 0 only after a full 2-step round: On [1, -9, 4], the round 0 -> 2 -> 2 has net round gain (-4) + 4 = 0, yet its rightward half dips by -4, requiring current_score >= 4 up front! Always enforce max(0, -right_move_gain, -hop_gain).
  • Turning at max(u, v) instead of the best suffix peak e >= max(u, v): A round u -> v may overshoot rightward past both u and v to capture a positive suffix before returning left to v, which is why compute_hop reads best_right_prefix[max(u, v)].
  • Performing extra loops on an earlier cell: Any extra loop beyond loops_needed_to_afford earns strictly less on source_cell than on target_cell since loop_gain[source_cell] < loop_gain[target_cell].
  • Treating p -> p as +0: Staying in place covers [p .. p] and adds board[p], not 0.

Alternative approaches

  • Step-by-step dynamic programming (O(k * n^2)): Track the highest score at each of the n indices after step 1, 2, ..., k. Far too slow for k = 4 * 10^8, but compact and reliable as a brute-force reference on small k in randomized tests.

Follow-up questions

  • How would you answer many move-budget queries (k_1, k_2, ..., k_q) against the same fixed board? Build all frontier[cell] lists once with rounds_allowed = infinity in O(n^3 log n) preprocessing time; because pruning only discards states dominated by states with <= rounds used, every optimal state for any smaller k survives in frontier[cell]. Each query k then inspects the O(n^2) kept pairs with rounds_used <= k // 2 and evaluates the linear finishing formula in O(n^2) time per query (or O(n log n) using a convex hull / upper envelope query per cell).
  • How could you output an optimal move schedule without listing hundreds of millions of individual steps? Save back-pointers (prev_cell, prev_state_idx, extra_loops) on each kept frontier entry along with the argmax index best_turn_cell[x] that realized best_right_prefix[x]. Since k reaches 4 * 10^8, emit a run-length-compressed schedule — e.g., [("loop", cell=0, turn=0, count=1), ("hop", from=0, turn=2, to=2), ("loop", cell=2, turn=2, count=249998)] — using O(n) memory and O(n) output records.
  • What overflow precautions are needed in fixed-width 64-bit languages if cell magnitudes could reach 4 * 10^8? With |board[i]| <= 4 * 10^8, loop_gain reaches 2 * 50 * 4 * 10^8 = 4 * 10^10 and the final score reaches 2 * 10^8 * 4 * 10^10 = 8 * 10^18, close to the signed 64-bit ceiling (2^63 - 1 ≈ 9.22 * 10^18). In C++ or Rust, compute intermediate products in int64_t / __int128 and evaluate ceiling division as 1 + (deficit - 1) / gain_per_loop rather than (deficit + gain_per_loop - 1) / gain_per_loop so the numerator cannot overflow before dividing.

Follow-up questions

Similar questions

More Imbue interview questions

All 1 Imbue questions →