LeetCode 2240: Number of Ways to Buy Pens and Pencils

MathEnumeration

Problem Description

Explanation:

To solve this problem, we can iterate through all possible combinations of pens and pencils that can be bought within the given total amount of money. We can use a nested loop to iterate through the number of pens and pencils bought, checking if the total cost is within the available money. If it is, we increment the count of ways to buy pens and pencils.

Algorithm:

  1. Initialize a variable ways to 0 to count the number of ways to buy pens and pencils.
  2. Iterate pens from 0 to total/cost1 (maximum number of pens that can be bought).
  3. Inside the pens loop, iterate pencils from 0 to total/cost2 (maximum number of pencils that can be bought).
  4. If the total cost of buying pens pens and pencils pencils is less than or equal to the total amount, increment the ways.
  5. Return the final count of ways.

Time Complexity:

The time complexity of this algorithm is O(total^2) as we are iterating through all possible combinations of pens and pencils.

Space Complexity:

The space complexity of this algorithm is O(1) as we are using only a constant amount of space for variables.

:

Solutions

class Solution {
    public int numWaysToBuyPensAndPencils(int total, int cost1, int cost2) {
        int ways = 0;
        for (int pens = 0; pens <= total / cost1; pens++) {
            for (int pencils = 0; pencils <= total / cost2; pencils++) {
                if (cost1 * pens + cost2 * pencils <= total) {
                    ways++;
                }
            }
        }
        return ways;
    }
}

Loading editor...