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
相关推荐
橙子199110162 分钟前
Kotlin 中的 Unit 类型的作用以及 Java 中 Void 的区别
java·开发语言·kotlin
yours_Gabriel9 分钟前
【登录认证】JWT令牌
java·开发语言·redis
为美好的生活献上中指14 分钟前
java每日精进 5.11【WebSocket】
java·javascript·css·网络·sql·websocket·网络协议
qq_141826973221 分钟前
python通过curl访问deepseek的API调用案例
java·数据库·python
lyw20561922 分钟前
微服务八股(自用)
java·开发语言
液态不合群30 分钟前
理解 C# 中的各类指针
java·开发语言·c#
一只码代码的章鱼32 分钟前
Java Spring MVC -01
java·spring·mvc
chenyuhao202443 分钟前
链表的面试题4之合并有序链表
数据结构·链表·面试·c#
Persistence___1 小时前
SpringBoot中的拦截器
java·spring boot·后端
嘵奇1 小时前
Spring Boot 跨域问题全解:原理、解决方案与最佳实践
java·spring boot·后端