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
0with total score0and may execute anywhere from0throughksteps before halting. Halting immediately after0steps yields score0. - Alternating directions: Numbering steps
t = 1, 2, ..., every odd-numbered step (t = 1, 3, 5, ...) moves rightward from the current indexpto any destinationqsatisfyingp <= q <= n - 1, and every even-numbered step (t = 2, 4, 6, ...) moves leftward frompto any destinationqsatisfying0 <= 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
pandqadds the inclusive subarray sumboard[min(p, q)] + ... + board[max(p, q)]to the running score. In particular, staying onp(q == p) addsboard[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 below0is 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 to6at index3. - Step 2 (left,
3 -> 1): adds4 - 2 + 5 = 7, bringing the score to13at index1. - Step 3 (right,
1 -> 3): adds4 - 2 + 5 = 7again, finishing with20.
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 index0, each adding2for a score of4(Step 2 must move leftward, so crossing to index2has to wait until Step 3). - Step 3 (right,
0 -> 2) adds2 - 11 + 7 = -2, leaving score4 - 2 = 2on index2. - All remaining
499,997steps stay on index2(2 -> 2) and add7apiece, reaching2 + 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^51 <= k <= 4 * 10^8- Results can reach
8 * 10^15, so 64-bit (or arbitrary-precision) integers are required.
Step-by-step walkthrough
Restate the rules and spot the monotonicity shortcut
We begin at index
0with score0and perform up toksteps (k <= 4 * 10^8) acrossnsigned board entries (n <= 50):- Odd steps (
1, 3, 5, ...) travel right: frompto anyqwithp <= q <= n - 1. - Even steps (
2, 4, 6, ...) travel left: frompto anyqwith0 <= q <= p. - Each step adds the inclusive subarray sum from
min(p, q)throughmax(p, q)— so remaining in place (q = p) still addsboard[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 (0steps gives0) 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,981One 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
>= 0starting from scoresalso stays>= 0starting froms' > s, finishings' - spoints higher.- Odd steps (
Why move-by-move DP is too slow
Using monotonicity, a direct dynamic programming baseline maintains
best_on[p]= maximum score reachable at cellpaftertsteps: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 answerEven with prefix sums,
O(k * n^2)work times out completely whenk = 4 * 10^8. On a board like[1, -400000, ..., -400000, 400000], the marker must camp at cell0earning+1per step for nearly19,000,000steps before crossing! We need to leap over long saving phases inO(1)time with division instead of ticking one step at a time.Pair moves into two-move rounds using prefix sums
Bundle consecutive steps into two-step rounds: a round from
start_cell(u) toend_cell(v) consists of one odd rightward stepu -> efollowed by one even leftward stepe -> v. For both halves to obey direction rules, the turning cellemust 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 overboard[l .. r]isprefix_sum[r + 1] - prefix_sum[l]. For turning celle: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_gainandhop_gainincrease wheneverprefix_sum[e + 1]increases! Consequently, choosinge >= max(u, v)with the largestprefix_sum[e + 1](stored inbest_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) earnsloop_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_neededWhy an optimal walk only climbs to better loop cells
Why relocate from cell
uto another cellvinstead of repeatingu's best loop? Only to reach a cell with a strictly higherloop_gain— either to farm points there until stepk, or as an intermediate stepping stone that accumulates cash faster toward an even richer cell later (such as cell1in[-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]:- A hop
u -> vnever exceeds the average of looping atuandv: becausebest_right_prefix[max(u, v)]is at most bothbest_right_prefix[u]andbest_right_prefix[v],hop_gain(u, v) <= (loop_gain[u] + loop_gain[v]) // 2. - A two-round detour
u -> w -> vnever beats a direct hopu -> vplus one loop: bothbest_right_prefix[max(u, w)]andbest_right_prefix[max(w, v)]are<= best_right_prefix[w], and their minimum equalsbest_right_prefix[max(u, v, w)] <= best_right_prefix[max(u, v)]. Summing them giveshop_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 cellb, swappingu -> w -> vfor one extra loop onbplus the direct hopu -> vspends 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_gainstrictly rises on every hop, no cell appears twice in the stepping-stone chain, capping chain length atn!- A hop
Jump over saving phases with ceiling division
Suppose we sit on cell
uwithcurrent_scoreand plan to hop to a higher-rate cellv(loop_gain[v] > loop_gain[u]). How many loops should we run onubeforehand?Strictly the minimum count required to reach
min_score_needed! Any extra loop performed onubeyond affordability could instead be performed onvafter the hop, earningloop_gain[v] > loop_gain[u]in the same round budget.When
current_score < min_score_neededandgain_per_loop > 0, closingdeficit = min_score_needed - current_scoretakesceil(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_loopPrune dominated states and run DP in increasing loop order
Distinct stepping-stone paths may land on the same cell
vwith different(rounds_used, score)pairs. If stateA = (r1, s1)uses no more rounds thanB = (r2, s2)(r1 <= r2),Acan spendr2 - r1loops atv(at rateloop_rate = max(loop_gain[v], 0)) to reachs1 + (r2 - r1) * loop_rateby roundr2.Thus
AdominatesBwhenever:s1 + (r2 - r1) * loop_rate >= s2 <=> s1 - r1 * loop_rate >= s2 - r2 * loop_rateSorting candidate states by
rounds_usedascending (and higherscorefirst on ties), we retain only states whose adjusted valuescore - rounds_used * loop_ratesets a strict new maximum. Processing target cells in ascendingloop_gainorder guarantees every validsource_cellfrontier is finalized beforetarget_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 keptSpend 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 allrounds_allowed - rounds_usedremaining two-step rounds looping oncell. - When
kis odd (k % 2 == 1), one final rightward step remains; fromcell, its best gain isbest_right_prefix[cell] - prefix_sum[cell] == loop_gain[cell] // 2. - When
loop_gain[cell] <= 0, stop immediately because additional steps fromcellcannot 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!- When
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 ofk. Computingprefix_sum,best_right_prefix, andloop_gaintakesO(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 cellvwithloop_gain[v] > 0exceeds the prior kept state's score by more thanloop_gain[v], while arrival scores after at mostn - 1hops stay undern * loop_gain[v], boundingfrontier[v]to at mostnstates (<= n - 1whenloop_gain[v] <= 0). Acrossntarget cells we inspect up tonsource cells and theirO(n)states — producingO(n^2)candidates — and sort them inO(n^2 log n)time, forO(n^3 log n)total (~125,000operations atn = 50). - Space:
O(n^2). Storingnfrontiers of at mostn(rounds_used, score)pairs each plus three length-narrays usesO(n^2)memory.
Edge cases
- Single cell (
n = 1): Every step is a zero-distance step on index0addingboard[0], returningk * board[0]ifboard[0] > 0and0otherwise. - All initial moves negative (Example 3,
[-6, 2, 3]): Every prefix sum starting at index0is negative, soloop_gain[0] < 0, no hop is reachable from(0, 0), andbest_score = 0(halting at0steps). k = 1:rounds_allowed = 0, so zero full rounds run; the odd-kbranch addsloop_gain[0] // 2 = best_right_prefix[0]when positive, matching the best prefix sum from index0.- Odd
k(k % 2 == 1): After spendingrounds_allowed - rounds_usedfull rounds on the final cellv, one rightward step remains and contributesloop_gain[v] // 2wheneverloop_gain[v] > 0. - Multi-hop stepping stones (
[-1, 1, -9, 5]): Index0hasloop_gain[0] = 0and cannot save up for index3directly, so it hops to index1(loop_gain[1] = 2), farms points there, and then hops to index3(loop_gain[3] = 10). - Large outputs (
8 * 10^15):50cells of4 * 10^5across4 * 10^8steps produce8 * 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 index0for nearly19million steps before crossing, so only ceiling division runs in time. - Checking
score >= 0only after a full 2-step round: On[1, -9, 4], the round0 -> 2 -> 2has net round gain(-4) + 4 = 0, yet its rightward half dips by-4, requiringcurrent_score >= 4up front! Always enforcemax(0, -right_move_gain, -hop_gain). - Turning at
max(u, v)instead of the best suffix peake >= max(u, v): A roundu -> vmay overshoot rightward past bothuandvto capture a positive suffix before returning left tov, which is whycompute_hopreadsbest_right_prefix[max(u, v)]. - Performing extra loops on an earlier cell: Any extra loop beyond
loops_needed_to_affordearns strictly less onsource_cellthan ontarget_cellsinceloop_gain[source_cell] < loop_gain[target_cell]. - Treating
p -> pas+0: Staying in place covers[p .. p]and addsboard[p], not0.
Alternative approaches
- Step-by-step dynamic programming (
O(k * n^2)): Track the highest score at each of thenindices after step1, 2, ..., k. Far too slow fork = 4 * 10^8, but compact and reliable as a brute-force reference on smallkin 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 withrounds_allowed = infinityinO(n^3 log n)preprocessing time; because pruning only discards states dominated by states with<=rounds used, every optimal state for any smallerksurvives infrontier[cell]. Each querykthen inspects theO(n^2)kept pairs withrounds_used <= k // 2and evaluates the linear finishing formula inO(n^2)time per query (orO(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 indexbest_turn_cell[x]that realizedbest_right_prefix[x]. Sincekreaches4 * 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)]— usingO(n)memory andO(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_gainreaches2 * 50 * 4 * 10^8 = 4 * 10^10and the final score reaches2 * 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 inint64_t/__int128and evaluate ceiling division as1 + (deficit - 1) / gain_per_looprather than(deficit + gain_per_loop - 1) / gain_per_loopso the numerator cannot overflow before dividing.
Follow-up questions
- How would you answer many move-budget queries (k_1, k_2, ..., k_q) against the same fixed board?
- How could you output an optimal move schedule without listing hundreds of millions of individual steps?
- What overflow precautions are needed in fixed-width 64-bit languages if cell magnitudes could reach 4 * 10^8?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array