当前位置: 首页 > news >正文

[LeetCode] 1518. Water Bottles

There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.

The operation of drinking a full water bottle turns it into an empty bottle.

Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.

Example 1:
Example 1
Input: numBottles = 9, numExchange = 3
Output: 13
Explanation: You can exchange 3 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 9 + 3 + 1 = 13.

Example 2:
Example 2
Input: numBottles = 15, numExchange = 4
Output: 19
Explanation: You can exchange 4 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 15 + 3 + 1 = 19.

Constraints:
1 <= numBottles <= 100
2 <= numExchange <= 100

换水问题。

超市正在促销,你可以用 numExchange 个空水瓶从超市兑换一瓶水。最开始,你一共购入了 numBottles 瓶水。

如果喝掉了水瓶中的水,那么水瓶就会变成空的。

给你两个整数 numBottles 和 numExchange ,返回你 最多 可以喝到多少瓶水。

思路

这是一道模拟题。题目说了每 numExchange 个空瓶可以换一瓶水,那么我们可以模拟这个过程,每喝掉 numExchange 瓶水,就去兑换一瓶水,直到 numBottles 喝光。注意兑换的水要加回 numBottles。

复杂度

时间O(n)
空间O(1)

代码

Java实现

class Solution {public int numWaterBottles(int numBottles, int numExchange) {int count = 0;while (numBottles >= numExchange) {count += numExchange;numBottles -= numExchange - 1;}return count + numBottles;}
}
http://www.gsyq.cn/news/14491.html

相关文章:

  • 题解:P14073 [GESP202509 五级] 数字选取
  • 张雪峰的事儿,大有文章
  • 技术内容思路构建Promot
  • # SICP学习笔记:计算机程序的构造与解释
  • 2025包装机厂家推荐榜单出炉:拉伸膜真空包装机,全自动真空包装机,滚动式真空包装机,食品真空包装机,气调包装机公司推荐!
  • 【半导体器件 | 笔记】金属氧化物半导体场效应晶体管(MOSFET)
  • 元人文AI场域:在有限与无限的纠缠中走向智慧文明
  • 【半导体器件 | 笔记】pn结二极管
  • Day2:Linux文件目录移到拷贝与vim编辑器使用指南
  • 【半导体物理 | 笔记】第八章 半导体表面与MIS结构
  • 【半导体物理 | 笔记】第四章 半导体的导电性
  • 【当前赛季】第36赛季:地狱魔王9月12日开启
  • 2025年9月 增值税进项税额,不可抵扣VS可抵扣全解析
  • 【Rust GUI开发入门】编写一个本地音乐播放器(14. 应用打包-制作安装程序) - Jordan
  • Visual Studio Code + Clangd 设置语法检查针对 C++的版本。
  • 示波器地、大地、电源地!地线着火?
  • 【Rust GUI开发入门】编写一个本地音乐播放器(13. 实现按键绑定) - Jordan
  • mem reduct 没有托盘图标
  • PEP8 规范
  • 【Rust GUI开发入门】编写一个本地音乐播放器(11. 支持动态明暗主题切换) - Jordan
  • US$54 AM29FXXX Adapter for CG Pro 9S12 Programmer
  • 2025CSP-S晋级和英才计划入围后:我走过了哪些路
  • 【J+S 二十连测】-- 第十二套爆炸记
  • 2025-2026-1 CS3311 软件工程 个人项目第一版已发布
  • 2025年10.1~10.6日信息竞赛计划安排表
  • 9. Spring AI 当中对应 MCP 的操作 - Rainbow
  • 随机采样研究随笔
  • springboot+vue心理健康服务小程序(源码+文档+调试+基础修改+答疑) - 详解
  • MacOS拉取git代码报.DS_Store 冲突修复
  • ARL灯塔搭建