← All challenges

Max Path with Threshold Constraint

Grid / Path (Advanced) ★★★☆

Maximum-sum path through a 6×6 patrol grid (right/down only), constrained to visit at least one high-priority zone (cell value ≥ 50).

A1:F6 is a 6×6 grid of patrol zone scores. A patrol team enters at A1, moves only right or down at each step, and accumulates the score of every zone it walks through (including start and end).

A patrol is only valid if it passes through at least one high-priority zone — defined as any cell with value ≥ 50. Output the maximum total score of any valid patrol from A1 to F6. If no valid path exists, return 0.

The unconstrained maximum on this grid is 263, but that route bypasses every high-priority zone entirely, so it doesn’t qualify. The formula has to carry a “have I visited a high-priority cell yet” flag through every recursive branch and disqualify any path that reaches the goal still flagged false.

Input

Range A1:F6

ABCDEF
1 131219192260
2 81221203514
3 23342173012
4 192113183126
5 103433143328
6 65332115721
Hint

Branching recursion that carries a 'valid' boolean through the calls. Out-of-bounds returns a sentinel (e.g. -9999), and reaching the goal returns the cell value only if valid is TRUE — otherwise returns the sentinel. Otherwise: take MAX of recursive children, propagate the sentinel if both children failed.

Solution
=LET(
  threshold, 50,
  tbl, A1:F6,
  ros, ROWS(tbl),
  cols, COLUMNS(tbl),
  bad, -9999,
  fx, LAMBDA(me, ro, co, valid,
    IF(OR(ro>ros, co>cols),
      bad,
      LET(
        cur, INDEX(tbl, ro, co),
        now_valid, OR(valid, cur >= threshold),
        IF(AND(ro=ros, co=cols),
          IF(now_valid, cur, bad),
          LET(
            d, me(me, ro+1, co, now_valid),
            r, me(me, ro, co+1, now_valid),
            best, MAX(d, r),
            IF(best = bad, bad, cur + best)
          )
        )
      )
    )
  ),
  result, fx(fx, 1, 1, FALSE),
  IF(result < 0, 0, result)
)