万圣节特卖|哈克兰克

问题描述

您希望从著名的在线视频游戏商店Mist购买视频游戏。

通常,所有游戏都以相同的价格(美元)出售。但是,他们计划在下个月举行季节性的万圣节大减价,从中您可以以更便宜的价格购买游戏。具体来说,您在销售过程中购买的第一款游戏将以美元出售,但您购买的所有后续游戏将以比之前购买的价格少的美元出售。这将一直持续到成本低于或等于美元,之后您购买的每款游戏都将花费美元。

例如,如果和,则以下是按顺序购买的第一款游戏的费用:

您的Mist钱包里有美元。您可以在万圣节大减价中购买多少个游戏?

我的代码是这个,我想知道为什么11/52测试用例失败了。

forEach

解决方法

只要您有剩余的钱,您就可以增加ct,但是如果剩下的钱不能支付游戏的费用,那么您就无法购买。

,

@Dialecticus是正确的。您缺少问题的关键信息。虽然我已经解决了相同的Hackerrank problem,并通过了所有测试用例。我只会共享伪代码,因为我的解决方案是使用JS而不是C ++。

counter = 0; // sales counter

// we still have enough money for a normal and a discounted game
while s >= m && s >= p

    // Apply discount after one game
    if counter > 0
        p = the larger price between the discounted price & min price       

    // deduct price from wallet
    s -= p;

    // record the sale
    counter++

return counter

我决定包含实际的JS代码,也许您可​​以翻译它。

let counter = 0;
while(s >= m && s >= p) {
    p = counter > 0 ? Math.max(p - d,m) : p;
    s -= p;
    counter++;
}
return counter;
,

为什么不使用公式呢?像这样:

if (p > s)
  return 0;

int t = min(
  ceil((p - m) / (float)d),floor((sqrt(8 * ceil((s - p) / (float)d) + 1) - 1) / 2)
);

return t + floor((s - (p * t - d * t * (t - 1) / 2)) / m);