#2931

Maximum Spending After Buying Items

Hard
ArrayGreedySortingHeap (Priority Queue)MatrixHeapGreedy
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 approach uses a max-heap to efficiently track and retrieve the rightmost available items across all shops. This allows us to always buy the most expensive item available for each day, maximizing the total spending.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a max-heap to store items along with their calculated costs for each day.
  2. 2Step 2: For each shop, push the rightmost item into the heap with its cost for day 1.
  3. 3Step 3: For each day, pop the item with the maximum cost from the heap, add it to the total spending, and push the next rightmost item from the same shop into the heap.
solution.py19 lines
1# Full working Python code
2import heapq
3
4values = [[8,5,2],[6,4,1],[9,7,3]]
5
6def maxSpendingOptimal(values):
7    total_spending = 0
8    m, n = len(values), len(values[0])
9    max_heap = []
10    for i in range(m):
11        heapq.heappush(max_heap, (-values[i][n-1], i, n-1))
12    for day in range(1, m * n + 1):
13        cost, shop, item = heapq.heappop(max_heap)
14        total_spending += -cost * day
15        if item > 0:
16            heapq.heappush(max_heap, (-values[shop][item - 1], shop, item - 1))
17    return total_spending
18
19print(maxSpendingOptimal(values))

Complexity note: The complexity is O(n log n) due to the heap operations, where n is the total number of items across all shops.

  • 1Using a max-heap allows efficient retrieval of the most expensive item available.
  • 2The greedy approach ensures that we maximize spending each day.

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