You work at a bakery, and every day you make pastries. You make 100 of each of several different types. However customers are less predictable. Some days they order all of one kind of pastry and you run out, some days they order hardly any and you have some left over. So your boss has made up a chart which tells you how many days each type of pastry can last before it's too old and can't be sold anymore. When there are leftover pastries the customers will always buy the freshest pastries first.
As an example lets use donuts, which (according to your boss's chart) can be sold 2 days after they are baked. Lets say you start the week with 0 donuts left over and the following are the orders for 5 days:
Mon | Tue | Wed | Thu | Fri |
---|---|---|---|---|
25 | 75 | 55 | 155 | 215 |
- On Monday you bake 100 donuts and sell 25, you have 75 left over.
- On Tuesday you bake 100 donuts and sell 75. Since customers prefer fresh donuts, all 75 donuts sold were ones baked on Tuesday. You have 75 still left over from Monday and 25 left over from Tuesday.
- On Wednesday you bake 100 donuts and sell 55. Since 55 is less than 100, all the donuts sold are fresh from that day. The 75 from Monday are now 2 days old and have to be thrown out. You have 25 still left from Tuesday and 45 from Wednesday.
- On Thursday you bake 100 donuts, and get 155 orders. The 100 fresh donuts get sold first, leaving 55 more orders to be filled, you sell all 45 donuts from Wednesday leaving 10 more orders which can be filled with donuts from Tuesday. At the end of the day you have 15 donuts from Tuesday which have to be thrown out.
- On Friday you bake 100 more donuts and get 215 orders. You only have 100 donuts so you only sell 100 donuts.
Challenge
Your program will take as input the number of days a particular pastry lasts (e.g. 2 for donuts) and the number of orders for that pastry each day over a period of time. The output will be how many pastries will be sold over that period of time.
This is code-golf so the goal is to minimize the size of your source code as measured in bytes.
Test cases
1 [100,100,100] -> 300
1 [372,1920,102] -> 300
1 [25,25,25] -> 75
1 [25,100,120] -> 225
1 [25,100,100,120] -> 325
1 [0,200] -> 200
1 [0,175,75] -> 250
1 [75,150,150] -> 300
1 [0,101,199]-> 201
1 [200,0] -> 100
2 [100,100,100] -> 300
2 [372,1920,102] -> 300
2 [25,25,25] -> 75
2 [25,100,120] -> 245
2 [25,100,100,120] -> 325
2 [0,200] -> 200
2 [0,175,75] -> 250
2 [75,150,150] -> 300
2 [0,101,199]-> 300
2 [200,0] -> 100