点燃蜡烛的最大天数

时间:2015-09-18 05:36:34

标签: arrays sorting puzzle

你被赋予了n个蜡烛的高度。第一天你点燃一根蜡烛第二天你需要点燃两根蜡烛第三天你需要点燃三根蜡烛直到可能。点燃蜡烛后,蜡烛的高度每天减去1个。你也可以熄灭你想要的任何蜡烛,但只能在一天结束时。所以你需要告诉最大天数,你可以继续点燃蜡烛。

Example : there are three candles of heights {2 ,2 ,2 }  
Answer : 3  
1.You light first candle on day one. heights -> {1,2,2}  
2.You light second and third and extinguish first one . heights ->{1, 1,1}  
3.You light all the candles. heights -{0,0,0}  

我在一个博客上找到了解决方案:

对array.Start进行排序,每天从最大值开始添加一个元素并减去所需的蜡烛数。所以2,2,2

Day 1: 2-1 = 1 Day 2: 1+2-2 = 1 Day 3: 1+2-3 = 0  
Answer is: 3  
But for 1,1,1 this algorithm will fail as answer should be 2.  

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

前两天它点燃了1 + 2 = 3个蜡烛单位 在那3个单位/天之后。

So if you want to lit a candle for 5 days , total unit of candle must be = 3 unit (for two days) + 
(3 * 3) (for rest of three days)
= 12 unit,
so you either need 3 candles of 4 unit , or 4 candles of 3 unit or 6 candles of 2 unit or 12 candles of 1 unit.

Hence, if h = number of height and n = number of candles(must be greater than 2)
then your equation will be number of days = (((h * n) - 3)/3) + 2
= (h * n)/3 + 1
<(>(h * n) - 3)/ 3)+ 2,-3前两天减少(3个单位),因为它在等式中以常数+2(天)加入。

如果蜡烛的数量大于或等于3.beaceuse,如果只有一根无限高度的蜡烛,那么这个等式只会满足。在第二天你不能点燃两次。 所以如果n <= 2天数将是n;

So complete equation will be:

if n <= 2 : number of days = n;
if n > 2 : number of days = (h * n)/3 + 1; 

答案 1 :(得分:0)

我今天向学生们提出了这个问题,这是我提出的解决方案。它在O(n)中运行(实际上它在O(金额)时间b / c中运行,这里的高度是一个非因素。你可以永远燃烧的天数比你有蜡烛b / c的金额+ 1天你即使你有足够的蜡烛,也不会有足够的实际蜡烛燃烧。)

public static int getAmtOfBurnDays(int height, int amount){
    int totalDaysThatWhereBurned = 0;

    int totalPiecesLeft = height * amount;

    while (totalDaysThatWhereBurned < amount){

        if(totalPiecesLeft < 0) break;

        totalDaysThatWhereBurned++;

        totalPiecesLeft -= totalDaysThatWhereBurned;
    }

    return totalDaysThatWhereBurned;
}