712575. Chocolates Pickup
Chocolates Pickup
Slug: chocolates-pickup
Difficulty: Hard
Topic Tags: Dynamic Programming
Company Tags: None
Summary
In this problem, we are given a 2D array chocolates where each cell represents the quantity of chocolates available at a particular day and at a particular store. Our task is to find out the maximum quantity of chocolates that can be picked up from all stores on a single day.
The key concepts involved in this problem are dynamic programming, which helps us solve this problem efficiently by breaking it down into smaller subproblems and solving each one only once.
Detailed Explanation
To solve this problem, we will use dynamic programming. We will maintain two arrays dp and prev. The array dp[i] represents the maximum quantity of chocolates that can be picked up on day i, and the array prev[i] stores the previous day's quantity that contributes to the current day's total.
Here is a step-by-step breakdown of the solution:
- Initialize
dp[0] = 0because we cannot pick up any chocolates on the first day. - For each subsequent day, calculate
dp[i] = max(dp[i-1], prev[i-1]) + prev[i-1]. This is because the maximum quantity of chocolates that can be picked up on a particular day is either the same as the previous day or the sum of the previous day's total and the current day's quantity. - Finally, return
dp[n-1], wherenis the number of days.
Here is an ASCII art diagram to illustrate this:
dp[0] = 0
dp[1] = prev[0]
dp[2] = max(dp[1], prev[1]) + prev[1]
...
dp[n-1] = max(dp[n-2], prev[n-2]) + prev[n-2]
Time complexity: O(n) Space complexity: O(1)
Optimized Solutions
Java
int chocolatesPickup(int[][] chocolates) {
int n = chocolates.length;
int[] dp = new int[n];
int[] prev = new int[n];
dp[0] = 0;
for (int i = 1; i < n; i++) {
dp[i] = Math.max(dp[i-1], prev[i-1]) + prev[i-1];
}
return dp[n-1];
}