LeetCode 2431: Maximize Total Tastiness of Purchased Fruits
Problem Description
Explanation:
To maximize the total tastiness of purchased fruits, we can use a dynamic programming approach. We can create a 2D array to store the maximum total tastiness that can be achieved at each store and at each level of tastiness. We iterate through each store and each level of tastiness, calculate the maximum total tastiness that can be achieved at the current store and level of tastiness by either buying or not buying the fruit, and update the corresponding cell in the 2D array. In the end, we return the maximum total tastiness that can be achieved.
- Initialize a 2D array
dp
of size (n+1) x (t+1) where n is the number of stores and t is the maximum level of tastiness. - Initialize
maxTastiness
to 0. - Iterate through each store from 1 to n:
- For each store, iterate through each level of tastiness from 1 to t:
- Calculate the maximum total tastiness that can be achieved at the current store and level of tastiness by either buying or not buying the fruit.
- Update the corresponding cell in the
dp
array with the maximum total tastiness. - If the current total tastiness is greater than
maxTastiness
, updatemaxTastiness
with the current total tastiness.
- For each store, iterate through each level of tastiness from 1 to t:
- Return
maxTastiness
. :
Solutions
class Solution {
public int maximizeTastiness(int n, int t, int[] tastiness, int[] store, int[] price) {
int[][] dp = new int[n + 1][t + 1];
int maxTastiness = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= t; j++) {
dp[i][j] = dp[i - 1][j];
if (j >= tastiness[i - 1]) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - tastiness[i - 1]] + store[i - 1] - price[i - 1]);
}
maxTastiness = Math.max(maxTastiness, dp[i][j]);
}
}
return maxTastiness;
}
}
Loading editor...