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
相关推荐
cfm_29141 分钟前
Redis五大基本数据结构底层了解
数据结构·数据库·redis
如竟没有火炬7 分钟前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
Jinkxs28 分钟前
Java 跨域14-Java 与区块链(Hyperledger)集成
java·开发语言·区块链
8Qi838 分钟前
LeetCode 1143 & 718:最长公共子序列 / 最长重复子数组
算法·leetcode·职场和发展·动态规划
晨曦中的暮雨1 小时前
Golang速通(Javaer版)
java·开发语言·后端·golang
七老板的blog2 小时前
当 Spring StateMachine 遇见大模型:构建工业级 AI 写作流水线
java·人工智能·spring
想吃火锅10052 小时前
【leetcode】1.两数之和js版
javascript·算法·leetcode
云烟成雨TD2 小时前
Spring AI 1.x 系列【46】MCP Security 模块
java·人工智能·spring
CRMEB系统商城2 小时前
CRMEB多商户系统(Java)v2.3公测版发布
java·开发语言·人工智能·小程序·开源·php
sinat_255487812 小时前
第七部分。介绍MVC(模型-视图-控制器)模式
java·ide·http·tomcat·intellij-idea