Ninja's training

Dynamic Programming 2D DP Medium
  • This programming problem is an example of dynamic programming, a commonly used problem-solving approach in software development
  • The concept of maximizing merit points over a range of choices without repeating the same activity, is similar to the real-world challenges that software like Google Calendar or Apple Health face
  • These apps need to suggest optimal fitness or productivity schedules based on a user's availability and preferences, ensuring a range of activities are covered without repetition on consecutive days
  • Such problems are solved using dynamic programming algorithms, just like this ninja training schedule problem

A ninja has planned a n-day training schedule. Each day he has to perform one of three activities - running, stealth training, or fighting practice. The same activity cannot be done on two consecutive days and the ninja earns a specific number of merit points, based on the activity and the given day.


Given a n x 3-sized matrix, where matrix[i][0], matrix[i][1], and matrix[i][2], represent the merit points associated with running, stealth and fighting practice, on the (i+1)th day respectively. Return the maximum possible merit points that the ninja can earn.

Examples:

Input: matrix = [[10, 40, 70], [20, 50, 80], [30, 60, 90]]

Output: 210

Explanation:

Day 1: fighting practice = 70

Day 2: stealth training = 50

Day 3: fighting practice = 90

Total = 70 + 50 + 90 = 210

This gives the optimal points.

Input: matrix = [[70, 40, 10], [180, 20, 5], [200, 60, 30]]

Output: 290

Explanation:

Day 1: running = 70

Day 2: stealth training = 20

Day 3: running = 200

Total = 70 + 20 + 200 = 290

This gives the optimal points.

Input: matrix = [[20, 10, 10], [20, 10, 10], [20, 30, 10]]

Constraints

  • 1 <= n <= 104
  • n == number of rows in matrix
  • 3 == number of columns in matrix
  • 0 <= matrix[i][j] <= 1000

Hints

  • "Let dp[i][j] be the maximum merit points possible on day i if the ninja performs activity j (j ∈ {0,1,2}). The ninja must pick an activity different from the previous day's to maximize points. The final answer is the maximum value from the last row of dp"
  • "A recursive approach without memoization leads to exponential complexity (O(3^n)) since we explore all choices. Using dynamic programming (O(n)), we store computed results in dp[][] to avoid redundant calculations."

Company Tags

Salesforce Qualcomm PwC Seagate Technology HCL Technologies Activision Blizzard Twilio Ernst & Young DoorDash OYO Rooms Zomato American Express Robinhood Optum Walmart Square Philips Healthcare Roblox NVIDIA Siemens Healthineers Teladoc Health Stripe Rakuten MongoDB PayPal Google Microsoft Amazon Meta Apple Netflix Adobe