Problem Summary
Given prices of a house in N years, find the minimum loss if we first buy it and then sell it at a lower price.
Solution 1
Suppose we sell the house on day i, then we only need to find the price just above price[i], from price[1],price[2],…,price[i-1].
If we use C++’s set container, we can keep prices in order, then we can use binary search to find the one we need.
Solution 2
This problem can also be solved using greedy.
First, we sort all years according to the prices.
Code for Solution 1
|
|
Code for Solution 2
|
|