BudiBadu Logo

Glow Market Profit Planner

Dynamic Programming Hard 1 views
Like29

The glow market merchant can buy one lantern bundle per night and hold any number of them However every sale requires a One-Night Cooldown before buying again Your mission in Glow Market Profit Planner is to find the maximum possible profit over a season Every buy must be paired with a later sale and skipping nights is allowed The secret sauce here is Dynamic Programming DP You track three states for each day Hold best profit with a bundle Sold just sold and Reset ready to buy Because of the cooldown you can only move from Sold to Reset on the next day before buying again This approach allows you to decide exactly when to strike for peak prices while following the festival charter rules If the market never rises or the list is empty return zero It s the ultimate way to handle state-based transaction logic while ensuring nightly showcases remain sustainable for the guild Because this is a counting optimization-style challenge dynamic programming is usually the safest approach define what each index or state means initialize valid base states and make transitions explicit If the problem uses modulo arithmetic apply modulo at every accumulation step so large intermediate totals never corrupt the final answer At hard difficulty hidden tests usually combine scale with edge behavior so the implementation must be both asymptotically efficient and logically strict Define transitions unambiguously prevent stale-state contamination and confirm tie-breaking or fallback rules

Examples

Example 1
Input
prices = [1,2,3,0,2]
Output
3
Explanation

Buy on day 1, sell on day 3, cooldown day 4, buy day 4, sell day 5.

Example 2
Input
prices = []
Output
0
Explanation

No trading nights yield zero profit.

Example 3
Input
prices = [2,1,4]
Output
3
Explanation

Buy on day 2 and sell on day 3 after waiting through the first decline.

Algorithm Flow

Recommendation Algorithm Flow for Glow Market Profit Planner - Budibadu
Recommendation Algorithm Flow for Glow Market Profit Planner - Budibadu

Best Answers

java
class Solution {
    public int calculate_max_profit(int[] prices) {
        if (prices.length == 0) return 0;
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int p : prices) {
            if (p < minPrice) minPrice = p;
            else if (p - minPrice > maxProfit) maxProfit = p - minPrice;
        }
        return maxProfit;
    }
}