708157. Maximum Number of Toys

Hard

Maximum Number of Toys

Summary

The problem "Maximum Number of Toys" requires you to find the maximum number of toys that can be purchased given a set of prices and a budget. This is an optimization problem, as you need to maximize the number of toys while staying within the budget.

Detailed Explanation

To solve this problem, we will use dynamic programming. The idea is to create a table where each cell represents the maximum number of toys that can be purchased with a certain amount of money. We start by initializing the first row and column of the table, then fill in the rest of the table based on the previous rows.

Here's the step-by-step breakdown:

  1. Initialize a 2D array dp with dimensions (budget + 1) x (num_toys + 1) where dp[i][j] represents the maximum number of toys that can be purchased with i amount of money and considering the first j toys.
  2. Fill in the first row and column of the table: dp[0][j] = 0 for all j, as you cannot purchase any toys with a budget of 0, and dp[i][0] = i / price[0] for all i, as you can always purchase at least one toy per unit of money.
  3. Fill in the rest of the table: dp[i][j] = max(dp[i - 1][k] + 1) for k from 0 to j. This means that if you have enough money to purchase at least one more toy, then do so and update the maximum number of toys.
  4. The maximum number of toys is stored in dp[budget][num_toys].

Here's an ASCII art diagram illustrating the dynamic programming approach:

  +--------+--------+--------+
  |  0    | 1      | 2      |
  +--------+--------+--------+
  |  10   | 5      | 3      |
  | 20    | 4      | 2      |
  | 30    | 3      | 1      |
  | ...   | ...    | ...    |
  +--------+--------+--------+

Time complexity: O(budget * num_toys) Space complexity: O(budget * num_toys)

Optimized Solutions

Java

View on GeeksforGeeks
public int maxToys(int[] prices, int budget) {
    int[][] dp = new int[budget + 1][prices.length + 1];
    for (int i = 0; i <= budget; i++) {
        dp[i][0] = i / prices[0];
    }
    for (int j = 0; j <= prices.length; j++) {
        dp[0][j] = 0;
    }
    for (int i = 1; i <= budget; i++) {
        for (int j = 1; j <= prices.length; j++) {
            dp[i][j] = Math.max(dp[i - 1][k] + 1) for k from 0 to j);
        }
    }
    return dp[budget][prices.length];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.