Leetcode #2431: Maximize Total Tastiness of Purchased Fruits
In this guide, we solve Leetcode #2431 Maximize Total Tastiness of Purchased Fruits in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
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:
- Buy first fruit without coupon, so that total price = 0 + 10 and total tastiness = 0 + 5.
- Buy second fruit with coupon, so that total price = 10 + 10 and total tastiness = 5 + 8.
- Do not buy third fruit, so that total price = 20 and total tastiness = 13.
It can be proven that 13 is the maximum total tastiness that can be obtained.
Python Solution
class Solution:
def maxTastiness(
self, price: List[int], tastiness: List[int], maxAmount: int, maxCoupons: int
) -> int:
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
The time complexity is , where is the number of fruits. The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.