EKO - Eko

Lumberjack Mirko needs to chop down M metres of wood. It is an easy job for him since he has a nifty new woodcutting machine that can take down forests like wildfire. However, Mirko is only allowed to cut a single row of trees.

Mirko‟s machine works as follows: Mirko sets a height parameter H (in metres), and the machine raises a giant sawblade to that height and cuts off all tree parts higher than H (of course, trees not higher than H meters remain intact). Mirko then takes the parts that were cut off. For example, if the tree row contains trees with heights of 20, 15, 10, and 17 metres, and Mirko raises his sawblade to 15 metres, the remaining tree heights after cutting will be 15, 15, 10, and 15 metres, respectively, while Mirko will take 5 metres off the first tree and 2 metres off the fourth tree (7 metres of wood in total).

Mirko is ecologically minded, so he doesn‟t want to cut off more wood than necessary. That‟s why he wants to set his sawblade as high as possible. Help Mirko find the maximum integer height of the sawblade that still allows him to cut off at least M metres of wood.


The first line of input contains two space-separated positive integers, N (the number of trees, 1 ≤ N ≤ 1 000 000) and M (Mirko‟s required wood amount, 1 ≤ M ≤ 2 000 000 000).

The second line of input contains N space-separated positive integers less than 1 000 000 000, the heights of each tree (in metres). The sum of all heights will exceed M, thus Mirko will always be able to obtain the required amount of wood.


The first and only line of output must contain the required height setting.


4 7
20 15 10 17

5 20
4 42 40 26 46


hide comments
mr_ashish: 2020-06-29 14:53:30

AC in one go :)

vraj_parikh_01: 2020-06-24 19:56:34

Nice problem for binary search

Last edit: 2020-06-24 19:57:24
kumar_anubhav: 2020-06-20 11:45:29

AC in one GO!!!

sujay008: 2020-06-18 17:11:04

if you are facing problem, i would say read about binary search... you can get great tutorials on youtube, look for concept not the answer

ramnathsaigal: 2020-06-07 15:33:55

Poor test cases...
if your answer is accepted check this test cases..
4 16
3 5 7 9
Ans is 2 :)

or test case:
4 2
1 3 8 9
Ans is 7 :)

Last edit: 2020-06-07 15:35:36
vinayak_26: 2020-06-03 12:38:32

AC in one go :-D..

lakshya_: 2020-06-03 09:26:27

@nguyenvietan yes , i solved it in (log(max_height)*log(n))
I solved it using binary search and prefix sum.

karthik_2: 2020-06-02 06:31:17

accepted in one go

nguyenvietan: 2020-05-24 10:12:10

I solved it in O(Nlog(H)), where N is the number of trees, H is the max height over all trees. Could any one show me how to solve it in less than O(Nlog(H)) ? Thanks.

yash_999: 2020-05-16 02:28:47

AC in one go :-)

Added by:ghorvat
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Resource:COCI 2011/2012