2个饮料瓶可以换1瓶饮料,4个瓶盖可以换1瓶饮料,1瓶饮料1块钱,问10块钱最多能买喝几瓶饮料。
public static void main(String[] args) { int bottle = 10, top = 10, temp = 10, num = 10; while (temp > 0){ temp = bottle / 2 + top / 4; num = num + temp; bottle = bottle % 2 + temp; top = top % 4 + temp; } System.out.println(num); }
初始时能够买到10瓶,会产生10个瓶子,10个瓶盖,每一轮循环用temp表示这轮能产生多少瓶新饮料。其实是个很简单的算法。我也看到很多有递归的实现。个人觉得我这个方法从理解,空间复杂度,时间复杂度都算不错。如有错误之处望不吝赐教!