712575. Chocolates Pickup

Hard

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:

  1. Initialize dp[0] = 0 because we cannot pick up any chocolates on the first day.
  2. 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.
  3. Finally, return dp[n-1], where n is 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

View on GeeksforGeeks
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];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.