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 Salesman Profit: Select Best Offers01234Houses 0 to n-1Offer 1: [0,2,1] - 1 goldOffer 2: [1,3,2] - 2 goldOffer 3: [3,4,3] - 3 goldSelect non-overlapping offers 1 and 3Maximum Profit: 1 + 3 = 4 gold
Understanding the Visualization
1
Input
Houses 0 to n-1 and buyer offers [start, end, gold]
2
Constraint
No house can be sold to multiple buyers
3
Optimize
Select offers that maximize total gold earned
Key Takeaway
🎯 Key Insight: This is weighted interval scheduling - sort by end time and use DP with binary search
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