Ninja's training
Pattern: 2D grid DP
Each day the ninja does one of three activities, never the same as the day before. Keep, for each activity, the most points if today ends with it: yesterday's best among the other two activities plus today's points.
The problem
Over n days the ninja picks one of three activities each day, earning points[day][activity], but may not do the same activity two days in a row. Return the most points.
Think first
- What must you remember about yesterday?
- For today's activity t, which of yesterday's totals can you use?
- How many states per day?
Hints
Brute force, and why it fails
Try every schedule: 3 × 2ⁿ⁻¹.
The key insight
The only constraint links consecutive days, so three totals per day are enough.
Dry run
| best | 1 2 5 |
|---|
points [[1, 2, 5], [3, 1, 1], [3, 3, 3]]. Day 0: best = [1, 2, 5].
Step 1 of 3
The plan
best = points[0]
for each day: best[t] = points[day][t] + max(best[p] for p != t)
Complexity
- Time
O(n)- Space
O(1)
Nine small steps per day.
Edge cases
- One day: the largest value.
- Equal points.
- Two days.
I've built my logic, show the code
Java
class Solution {
public int ninjaTraining(int[][] points) {
int[] best = points[0].clone(); // best[t]: the most points so far if today's task is t
for (int day = 1; day < points.length; day++) {
int[] next = new int[3];
for (int t = 0; t < 3; t++) // today's task t must differ from yesterday's
for (int prev = 0; prev < 3; prev++) if (prev != t) next[t] = Math.max(next[t], best[prev] + points[day][t]);
best = next;
}
return Math.max(best[0], Math.max(best[1], best[2]));
}
}C++
class Solution {
public:
int ninjaTraining(vector<vector<int>>& points) {
vector<int> best(points[0]); // best[t]: the most points so far if today's task is t
for (size_t day = 1; day < points.size(); day++) {
vector<int> next(3, 0);
for (int t = 0; t < 3; t++) // today's task t must differ from yesterday's
for (int prev = 0; prev < 3; prev++) if (prev != t) next[t] = max(next[t], best[prev] + points[day][t]);
best = next;
}
return max(best[0], max(best[1], best[2]));
}
};Python
class Solution:
def ninjaTraining(self, points: list[list[int]]) -> int:
best = list(points[0]) # best[t]: the most points so far if today's task is t
for day in points[1:]:
best = [max(best[p] for p in range(3) if p != t) + day[t] for t in range(3)] # differ from yesterday
return max(best)Common mistakes
- Allowing the same activity twice.
- Overwriting best while still reading it.