#2830
Medium Algorithms Maximize the profit as the salesman
Array Hash Table Binary Search Dynamic Programming Sorting
38.0% acceptance
Feb 25, 2026
717
22
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 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 that different buyers can't buy the same house, and some houses may remain unsold.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn maximize_the_profit(n: i32, offers: Vec<Vec<i32>>) -> i32 {
let n = n as usize;
let mut by_end: Vec<Vec<(usize, i32)>> = vec![vec![]; n];
for o in &offers { by_end[o[1] as usize].push((o[0] as usize, o[2])); }
let mut dp = vec![0i32; n + 1];
for i in 1..=n {
dp[i] = dp[i-1];
for &(start, gold) in &by_end[i-1] {
dp[i] = dp[i].max(dp[start] + gold);
}
}
dp[n]
}
}