leetcode - 2139. Minimum Moves to Reach Target Score

Description

You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.

In one move, you can either:

  • Increment the current integer by one (i.e., x = x + 1).
  • Double the current integer (i.e., x = 2 * x).

You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.

Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.

Example 1:

复制代码
Input: target = 5, maxDoubles = 0
Output: 4
Explanation: Keep incrementing by 1 until you reach target.

Example 2:

复制代码
Input: target = 19, maxDoubles = 2
Output: 7
Explanation: Initially, x = 1
Increment 3 times so x = 4
Double once so x = 8
Increment once so x = 9
Double again so x = 18
Increment once so x = 19

Example 3:

复制代码
Input: target = 10, maxDoubles = 4
Output: 4
Explanation: Initially, x = 1
Increment once so x = 2
Double once so x = 4
Increment once so x = 5
Double again so x = 10

Constraints:

复制代码
1 <= target <= 10^9
0 <= maxDoubles <= 100

Solution

The optimal way to get to the target would be: increase to a certain point, and double it to get to the target. So to do this, we start from the target. If it's an odd number, use one increment operation to reduce it by 1. If it's even and we have double operations, divide it by 2.

Time complexity: min ⁡ ( m a x D o u b l e s , log ⁡ ( t a r g e t ) ) \min(maxDoubles, \log(target)) min(maxDoubles,log(target))

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
class Solution:
    def minMoves(self, target: int, maxDoubles: int) -> int:
        res = 0
        while target > 1 and maxDoubles > 0:
            if target & 1 == 1:
                target -= 1
            else:
                target //= 2
                maxDoubles -= 1
            res += 1
        return res + target - 1
相关推荐
云雀衔光4 小时前
Java Spring AI MCP:在 Spring 里把 AI 接上你的业务系统
java·开发语言·人工智能·后端·测试工具·spring
重生之小比特4 小时前
【Java SE】数据类型与变量
java·开发语言·python
苏渡苇4 小时前
Spring Insight 里如何对 Span 进行清洗
java·spring boot·后端·spring·系统监控
find1star4 小时前
LeetCode 54:螺旋矩阵——用四个边界模拟矩阵收缩
java·算法·leetcode·边缘计算·学习方法
Yeniden4 小时前
Java 后端从零到企业级:第1篇 Java 基础语法——变量、数据类型与运算符
java·开发语言·apache
邪修king4 小时前
Linux系统篇(二十三) 基础 IO:从“文件”到“文件描述符”,彻底理解重定向
android·java·linux
云雀衔光4 小时前
MCP + 应用生成:让 AI 直接产出可交互的应用
java·人工智能·测试工具·microsoft·交互·ai编程
Nuanyt4 小时前
JVM常见核心知识梳理02 类加载 字节码技术 双亲委派 Java内存模型 JMM 并发底层 volatile synchronized 常见排障与调优工具
java·开发语言·jvm
吞下星星的少年·-·4 小时前
LeetCode 热题 100 两数之和(哈希表)
算法·leetcode·哈希算法
Shan12055 小时前
经典算法题示例与详解:飞地的数量(二)
java·数据结构·算法