#2830

Maximize the Profit as the Salesman

Medium
ArrayHash TableBinary SearchDynamic ProgrammingSortingDynamic ProgrammingSortingInterval Scheduling
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses dynamic programming to efficiently calculate the maximum gold by considering each offer and the best possible outcome for the houses sold up to that point. By sorting the offers and using a DP array, we can avoid redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the offers based on the start index.
  2. 2Step 2: Initialize a DP array where dp[i] represents the maximum gold earned by selling houses up to index i.
  3. 3Step 3: For each offer, update the DP array considering the current offer and the best previous non-overlapping offer.
solution.py11 lines
1def maxGold(n, offers):
2    offers.sort()
3    dp = [0] * n
4    for start, end, gold in offers:
5        dp[end] = max(dp[end], (dp[start - 1] if start > 0 else 0) + gold)
6    for i in range(1, n):
7        dp[i] = max(dp[i], dp[i - 1])
8    return dp[-1]
9
10# Example usage
11print(maxGold(5, [[0,0,1],[0,2,2],[1,3,2]]))

Complexity note: The sorting step takes O(n log n) time, while filling the DP array takes O(n) time, leading to an overall complexity of O(n log n).

  • 1Understanding the overlap of offers is crucial to maximizing profit.
  • 2Dynamic programming can significantly reduce the time complexity by avoiding redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.