First deal with building sector 1, then sector 2, then sector 3 and so on. We can build sector 1 for price S and go on to sector 2. Or we can build sector 1 for price p[i] and go to sector (b[i]+1) for all i such that a[i] = 1 This intuition gives the following idea: Build a graph with (n + 1) nodes and the following directed edges: 1. (x, x + 1) with price S 2. (x + 1, x) with price 0 3. (a[i], b[i] + 1) with price p[i] Note the edges type 2, they allow us to overlap two offers. The shortest path from 1 to (n + 1) is the minimal price to build the whole wall.