Program to Find Out the Minimum Cost to Purchase All in Python

We need to find the minimum cost to purchase exactly one of every item from 0 to N-1. We have sets that contain ranges of items with purchase costs, and removals that let us discard extra items for a fee.

This problem can be solved using Dijkstra's shortest path algorithm by modeling it as a graph where each node represents the number of items we need to collect.

Understanding the Problem

Given:

  • sets: Each set [start, end, cost] lets us buy items from start to end (inclusive) for the given cost

  • removals: Cost to remove one instance of the i-th item

We need to end up with exactly one of each item (0 to N-1).

Algorithm Approach

We model this as a graph problem where:

  • Node i represents having collected items 0 through i-1

  • Buying a set moves us forward in the graph

  • Removal costs help us get rid of extra items

Example

import heapq
from collections import defaultdict

class Solution:
    def solve(self, sets, removals):
        N = len(removals)
        graph = [[] for _ in range(N + 1)]
        
        # Add edges for purchasing sets
        for s, e, w in sets:
            graph[s].append([e + 1, w])
        
        # Add edges for removing items (going backward)
        for i, r in enumerate(removals):
            graph[i + 1].append([i, r])
        
        # Dijkstra's algorithm
        pq = [[0, 0]]
        dist = defaultdict(lambda: float("inf"))
        dist[0] = 0
        
        while pq:
            d, e = heapq.heappop(pq)
            if dist[e] < d:
                continue
            if e == N:
                return d
            for nei, w in graph[e]:
                d2 = d + w
                if d2 < dist[nei]:
                    dist[nei] = d2
                    heapq.heappush(pq, [d2, nei])
        
        return -1

# Test the solution
ob = Solution()
sets = [
    [0, 4, 4],
    [0, 5, 12],
    [2, 6, 9],
    [4, 8, 10]
]
removals = [2, 5, 4, 6, 8]

result = ob.solve(sets, removals)
print(f"Minimum cost: {result}")
Minimum cost: 4

How It Works

The algorithm works by:

  1. Graph Construction: Create edges representing set purchases and item removals

  2. Dijkstra's Algorithm: Find the shortest path from state 0 (no items) to state N (exactly N items)

  3. State Transitions: Move forward by buying sets, move backward by removing excess items

Step-by-Step Trace

For the given example:

  • Start at state 0 (need to collect items 0-4)

  • Buy set [0, 4, 4]: Move to state 5 with cost 4

  • Remove item 4 with cost removals[4] = 8: Move to state 4 with total cost 12

  • The optimal path gives us cost 4

Conclusion

This solution uses Dijkstra's algorithm to model the purchase and removal process as a shortest path problem. The time complexity is O((N + S) log N) where S is the number of sets, making it efficient for finding the minimum cost to purchase exactly one of each item.

---
Updated on: 2026-03-25T13:56:19+05:30

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements