[LeetCode] Maximize Total Tastiness of Purchased Fruits

2431. Maximize Total Tastiness of Purchased Fruits

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.

For every integer i in range [0, n - 1]:

  • price[i] describes the price of ith fruit.
  • tastiness[i] describes the tastiness of ith fruit.

You want to purchase some fruits such that total tastiness is maximized and the total price does not exceed maxAmount.

Additionally, you can use a coupon to purchase fruit for half of its price (rounded down to the closest integer). You can use at most maxCoupons of such coupons.

Return the maximum total tastiness that can be purchased.

Note that:

  • You can purchase each fruit at most once.
  • You can use coupons on some fruit at most once.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int dp[1010][6];
public:
int maxTastiness(vector<int>& price, vector<int>& tastiness, int maxAmount, int maxCoupons) {
memset(dp,-1,sizeof dp);
dp[0][0] = 0;
int res = 0;
for(int i = 0; i < price.size(); i++) {
int p = price[i], t = tastiness[i];
for(int j = maxCoupons; j >= 0; j--) {
for(int k = maxAmount; k >= p / 2; k--) {
if(k >= p and dp[k-p][j] != -1) dp[k][j] = max(dp[k-p][j] + t, dp[k][j]);
if(j and dp[k-(p/2)][j-1] != -1) dp[k][j] = max(dp[k][j], dp[k-(p/2)][j-1] + t);
res = max(res, dp[k][j]);
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/10/PS/LeetCode/maximize-total-tastiness-of-purchased-fruits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.