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
相关推荐
毕设源码-赖学姐6 分钟前
【开题答辩全过程】以 花卉交易系统为例,包含答辩的问题和答案
java
We་ct8 分钟前
LeetCode 212. 单词搜索 II:Trie+DFS 高效解法
开发语言·算法·leetcode·typescript·深度优先·图搜索算法·图搜索
样例过了就是过了11 分钟前
LeetCode热题100 路径总和 III
数据结构·c++·算法·leetcode·链表
再难也得平16 分钟前
力扣41. 缺失的第一个正数(Java解法)
数据结构·算法·leetcode
weixin_7042660518 分钟前
Spring整合MyBatis(一)
java·spring·mybatis
翘着二郎腿的程序猿19 分钟前
Maven本地化部署与使用全指南
java·maven
历程里程碑20 分钟前
Linux 49 HTTP请求与响应实战解析 带http模拟实现源码--万字长文解析
java·开发语言·网络·c++·网络协议·http·排序算法
IronMurphy23 分钟前
【算法二十】 114. 寻找两个正序数组的中位数 153. 寻找旋转排序数组中的最小值
java·算法·leetcode
实心儿儿25 分钟前
算法2:链表的中间结点
数据结构·算法·链表
代码探秘者26 分钟前
【Java集合】ArrayList :底层原理、数组互转与扩容计算
java·开发语言·jvm·数据库·后端·python·算法