Maximize Total Tastiness of Purchased Fruits — LeetCode 2431 Python Solution

MediumLeetCode PremiumArrayDynamic Programming
Problem
#2431
Reading time
3 min

The problem

You are given two non-negative integer arrays price and tastiness, both arrays have the same length n. You are also given two non-negative integers maxAmount and maxCoupons.

Example

Input
price = [10,20,20], tastiness = [5,8,8], maxAmount = 20, maxCoupons = 1
Output
13
Explanation
It is possible to make total tastiness 13 in following way:

Python solution

Python
class Solution:
    def maxTastiness(
        self, price: List[int], tastiness: List[int], maxAmount: int, maxCoupons: int
    ) -> int:
        @cache
        def dfs(i, j, k):
            if i == len(price):
                return 0
            ans = dfs(i + 1, j, k)
            if j >= price[i]:
                ans = max(ans, dfs(i + 1, j - price[i], k) + tastiness[i])
            if j >= price[i] // 2 and k:
                ans = max(ans, dfs(i + 1, j - price[i] // 2, k - 1) + tastiness[i])
            return ans

        return dfs(0, maxAmount, maxCoupons)

Complexity

MeasureComplexity
TimeO(n \times maxAmount \times maxCoupons), where n is the number of fruits
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2431. Maximize Total Tastiness of Purchased Fruits is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2431. Maximize Total Tastiness of Purchased Fruits?
LeetCode 2431. Maximize Total Tastiness of Purchased Fruits is rated Medium on LeetCode.
What topics does LeetCode 2431. Maximize Total Tastiness of Purchased Fruits cover?
LeetCode 2431. Maximize Total Tastiness of Purchased Fruits is tagged Array and Dynamic Programming on LeetCode.
Is LeetCode 2431. Maximize Total Tastiness of Purchased Fruits a premium problem?
Yes. LeetCode 2431. Maximize Total Tastiness of Purchased Fruits is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview