BudiBadu Logo

Max Vacation Profit

Dynamic Programming Hard 14 views
Like14

A travel photographer plans a summer filled with short excursions Each day offers a different destination with its own enjoyment value but capturing a location takes effort after visiting one site the photographer needs a rest day before heading out again Given an array where each value represents the enjoyment for that day determine the maximum total enjoyment the photographer can earn while respecting a one-day cooldown after each excursion Visualize a calendar lined with sunrise hikes museum tours and mountain trails Some days promise breathtaking scenes worth the fatigue while others are quieter The challenge lies in selecting a sequence of outings that maximizes joy without ever heading out on back-to-back days Sometimes it is wiser to skip a high-enjoyment day if it allows you to string together a better series later If the array is empty no travel occurs Negative values represent exhausting days that should typically be avoided Dynamic programming helps the photographer remember how previous choices influence future opportunities ensuring the final itinerary delivers the highest possible total enjoyment When the task involves connectivity or route cost build adjacency carefully and guard against revisiting stale states Use a visited or best-distance structure to avoid repeated work and ensure unreachable scenarios return the required fallback value instead of partial traversal results 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

Examples

Example 1
Input
enjoyment = []
Output
0
Explanation

No days, no enjoyment.

Example 2
Input
enjoyment = [2,1,4,5,3,1,1,3]
Output
10
Explanation

Optimal plan is days 0,2,4,7: 2+4+3+3 = 12, but cooldown after day 4 prevents day 5, so best consistent plan yields 10.

Example 3
Input
enjoyment = [3,2,5,10,7]
Output
15
Explanation

Visit on days 0,2,4 (3+5+7) or days 1,3 (2+10); the maximum is 15.

Algorithm Flow

Recommendation Algorithm Flow for Max Vacation Profit - Budibadu
Recommendation Algorithm Flow for Max Vacation Profit - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int calculate_max_profit(int[][] jobs) {
        Arrays.sort(jobs, (a, b) -> a[1] - b[1]);
        int n = jobs.length;
        int[] dp = new int[n + 1];
        int[] ends = new int[n];
        for (int i = 0; i < n; i++) ends[i] = jobs[i][1];
        for (int i = 1; i <= n; i++) {
            int start = jobs[i-1][0];
            int profit = jobs[i-1][2];
            int idx = Arrays.binarySearch(ends, 0, i - 1, start);
            if (idx < 0) idx = -(idx + 1);
            else idx = idx + 1;
            dp[i] = Math.max(dp[i-1], dp[idx] + profit);
        }
        return dp[n];
    }
}