Maximize the Profit as the Salesman — LeetCode 2830 Python Solution
- Problem
- #2830
- Pattern
- Binary Search
- Reading time
- 2 min
- Source
- leetcode.com
The 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 ith buyer wants to buy all the houses from starti to endi for goldi amount of gold.
Example
- 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.
Python solution
class Solution:
def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int:
offers.sort(key=lambda x: x[1])
f = [0] * (len(offers) + 1)
g = [x[1] for x in offers]
for i, (s, _, v) in enumerate(offers, 1):
j = bisect_left(g, s)
f[i] = max(f[i - 1], f[j] + v)
return f[-1]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Binary Search
Halve the search space each step — over an array, or over the answer itself. LeetCode 2830. Maximize the Profit as the Salesman is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.
The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2830. Maximize the Profit as the Salesman?
- LeetCode 2830. Maximize the Profit as the Salesman is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2830. Maximize the Profit as the Salesman?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2830. Maximize the Profit as the Salesman?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2830. Maximize the Profit as the Salesman cover?
- LeetCode 2830. Maximize the Profit as the Salesman is tagged Array, Hash Table, Binary Search, Dynamic Programming and Sorting on LeetCode.