Maximize the Profit as the Salesman - Problem

You are given an integer n representing the number of houses on a number line, numbered from 0 to n - 1.

Additionally, you are given a 2D integer array offers where offers[i] = [starti, endi, goldi], indicating that the ith buyer wants to buy all the houses from starti to endi for goldi amount of gold.

As a salesman, your goal is to maximize your earnings by strategically selecting and selling houses to buyers.

Return the maximum amount of gold you can earn.

Note: Different buyers can't buy the same house, and some houses may remain unsold.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, offers = [[0,2,1],[1,3,2],[3,4,3]]
Output: 4
💡 Note: Select offers [0,2,1] and [3,4,3]. Houses 0-2 sold for 1 gold, houses 3-4 sold for 3 gold. Total = 1 + 3 = 4 gold.
Example 2 — No Overlaps
$ Input: n = 6, offers = [[0,1,2],[2,3,3],[4,5,4]]
Output: 9
💡 Note: All offers are non-overlapping, so select all: 2 + 3 + 4 = 9 gold.
Example 3 — Single Best Offer
$ Input: n = 3, offers = [[0,2,10],[1,2,1]]
Output: 10
💡 Note: Choose the single high-value offer [0,2,10] for maximum profit of 10 gold.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ offers.length ≤ 105
  • offers[i].length == 3
  • 0 ≤ starti ≤ endi ≤ n - 1
  • 1 ≤ goldi ≤ 103

Visualization

Tap to expand
Maximize the Profit as the Salesman INPUT n = 5 houses (0 to 4) 0 1 2 3 4 Offers Table Start End Gold Offer 1: 0 2 1 Offer 2: 1 3 2 Offer 3: 3 4 3 Offer Ranges: Offer 1: gold=1 Offer 2: gold=2 Offer 3: gold=3 Note: Offers 1,2 overlap ALGORITHM STEPS 1 Sort offers by end Group offers ending at same house position 2 Initialize DP array dp[i] = max gold selling houses 0 to i 3 For each house i: dp[i] = max(dp[i-1], dp[start-1] + gold) 4 Return dp[n-1] Maximum gold earned DP Table Calculation: 0 i=0 0 i=1 1 i=2 2 i=3 4 i=4 dp[2]=1 (Offer1), dp[3]=2 (Offer2) dp[4]=dp[2]+3=1+3=4 (Offer1+3) Best: Offer1 + Offer3 = 4 FINAL RESULT Optimal Selection 0 1 2 3 4 Offer 1 (gold=1) Offer 3 (gold=3) Gold Calculation: Offer 1 (0-2): 1 gold Offer 3 (3-4): 3 gold Total: 4 gold Output: 4 OK - Maximum Gold! No overlapping offers Key Insight: This is a weighted interval scheduling problem solved with Dynamic Programming. For each position i, we decide: skip all offers ending at i (take dp[i-1]), or take the best offer ending at i and add its gold to the optimal solution for non-overlapping houses (dp[start-1]). Time: O(n + m), Space: O(n + m). TutorialsPoint - Maximize the Profit as the Salesman | Optimal DP Solution
Asked in
Amazon 15 Google 12 Microsoft 8 Apple 6
21.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen