java算法买3瓶送1瓶_【算法】啤酒与瓶盖与空瓶(java)

题目描述:

啤酒2元一瓶 4个瓶盖能换1瓶啤酒,2个空瓶也能换1瓶啤酒,问:n元钱最多能喝几瓶酒?

解题思路:

在不能借瓶盖的情况下,第一种方法直接暴力求解。

/* 啤酒2元一瓶 4个瓶盖能换1瓶啤酒,2个空瓶也能换1瓶啤酒*/

/*n元钱最多能喝几瓶酒?*/

public class ForTest {

static class Solution {

public int canDrink(int money) {

int beer_num=0;

int lid_num=0;

int bottle_num=0;

int ans=0;

while ((money>0&&money%2==0)||lid_num>=4||bottle_num>=2){

if(money>0&&money%2==0){

beer_num=money/2;

lid_num=beer_num;

bottle_num=beer_num;

money-=2*beer_num;

ans+=beer_num;

}

if(lid_num>=4){

beer_num=lid_num/4;

lid_num=lid_num-beer_num*4+beer_num;

bottle_num+=beer_num;

ans+=beer_num;

}

if(bottle_num>=2){

beer_num=bottle_num/2;

lid_num+=beer_num;

bottle_num=bottle_num-beer_num*2+beer_num;

ans+=beer_num;

}

}

return ans;

}

}

public static void main(String[] args) {

Solution s=new Solution();

int ans=s.canDrink(10);

System.out.println(ans);

}

}

第二种方法用递归求解。

/* 啤酒2元一瓶 4个瓶盖能换1瓶啤酒,2个空瓶也能换1瓶啤酒*/

/*n元钱最多能喝几瓶酒?*/

public class ForTest {

static class Solution {

public int canDrink(int money, int lib_num, int bottle_num,int ans) {

if ((money <= 0 || money == 1) && lib_num < 4 && bottle_num < 2) {

return ans;

}else {

if (money > 0&&money!=1) {

ans++;

return canDrink(money - 2, lib_num + 1, bottle_num + 1,ans);

}

if (lib_num >= 4) {

ans++;

return canDrink(money, lib_num - 4 + 1, bottle_num + 1,ans);

}

if (bottle_num >= 2) {

ans++;

return canDrink(money, lib_num + 1, bottle_num - 2 + 1,ans);

}

return ans;

}

}

}

public static void main(String[] args) {

Solution s = new Solution();

int ans=s.canDrink(10, 0, 0,0);

System.out.println(ans);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值