MediumNo. 2431LeetCode Premium

Maximize Total Tastiness of Purchased Fruits — LeetCode 2431 Python Solution

Topics
Array, Dynamic Programming
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

PythonSolution
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

Time
O(n × maxAmount × maxCoupons), where n is the number of fruits
Space · auxiliary
O(n·m) or optimized

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

Related problems
No.ProblemDifficulty
2435Paths in Matrix Whose Sum Is Divisible by KHard
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium

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.

Free to download. Check it runs on your machine, then pick a plan.