Description
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.
Example 1:
Input: n = 5, offers = [[0,0,1],[0,2,2],[1,3,2]]
Output: 3
Explanation: There are 5 houses numbered from 0 to 4 and there are 3 purchase offers.
We sell houses in the range [0,0] to 1st buyer for 1 gold and houses in the range [1,3] to 3rd buyer for 2 golds.
It can be proven that 3 is the maximum amount of gold we can achieve.
Example 2:
Input: n = 5, offers = [[0,0,1],[0,2,10],[1,3,2]]
Output: 10
Explanation: There are 5 houses numbered from 0 to 4 and there are 3 purchase offers.
We sell houses in the range [0,2] to 2nd buyer for 10 golds.
It can be proven that 10 is the maximum amount of gold we can achieve.
Constraints:
1 <= n <= 10^5
1 <= offers.length <= 10^5
offers[i].length == 3
0 <= starti <= endi <= n - 1
1 <= goldi <= 10^3
Solution
A classical weighted interval scheduling problem, see here for more details.
A better and easier solution with same problem, see 1235. Maximum Profit in Job Scheduling
Sort the offers by end, and then dp. dp[i]
denotes the largest gold we can get when choosing offer[i]
. Transformation equation is:
d
p
[
i
]
=
max
(
d
p
[
i
−
1
]
,
o
f
f
e
r
s
[
i
]
[
2
]
+
d
p
[
j
]
)
dp[i] = \max(dp[i - 1], offers[i][2] + dp[j])
dp[i]=max(dp[i−1],offers[i][2]+dp[j])
where
o
f
f
e
r
[
j
]
[
1
]
<
o
f
f
e
r
[
i
]
[
0
]
offer[j][1] < offer[i][0]
offer[j][1]<offer[i][0], that is, offer[j]
is the largest index that we can choose offer[i]
. Since we sort the end from small to large, use binary search here.文章来源:https://www.toymoban.com/news/detail-663724.html
Time complexity:
o
(
n
log
n
)
o(n\log n)
o(nlogn)
Space complexity:
o
(
n
)
o(n)
o(n)文章来源地址https://www.toymoban.com/news/detail-663724.html
Code
class Solution:
def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int:
offers.sort(key=lambda x: x[1])
# p list contains the largest indexs that we could choose offer[i]
p = [-1] * len(offers)
ends = list(item[1] for item in offers)
for i in range(1, len(p)):
index = bisect.bisect_left(ends, offers[i][0])
p[i] = index - 1
dp = [0] * len(offers)
dp[0] = offers[0][2]
for i in range(1, len(dp)):
dp[i] = max(dp[i - 1], offers[i][2] + (dp[p[i]] if p[i] >= 0 else 0))
return max(dp)
到了这里,关于leetcode - 2830. Maximize the Profit as the Salesman的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!