Debby loves eating all kind of pastry, she also likes to make long term financial plan to optimize her savings. She would be very happy if you could help her find the most stably-priced type of pastry. As a financial expert, she has devised a way to calculate the stability.
Given months of price data for types of pastry, sort the pastries by their price in ascending order for each month, and record their position (i.e. the cheapest item has ).
The volatilty of each pastry for each month is defined as their position difference relative to the previous month.
Formally: , where .
Find the most stable pastry by minimizing the sum of volatility of each pastry: .
Break tie using the order from the original input, the type of pastry that appears first is preferred.
Debby is also an expert in programming and is very nice to give you a short C++ reference which might be useful:
Hint: The most stable pastry is the one which its relative price position in each month changes the least.
Input
Output
Input
Output