当前位置: 首页> 游戏> 评测 > 专业网站有哪些平台_商城网站有哪些_单页网站怎么优化_如何在网上推广自己

专业网站有哪些平台_商城网站有哪些_单页网站怎么优化_如何在网上推广自己

时间:2025/7/9 23:30:37来源:https://blog.csdn.net/sinat_41679123/article/details/144656371 浏览次数:0次
专业网站有哪些平台_商城网站有哪些_单页网站怎么优化_如何在网上推广自己

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

class Solution:def minMoves(self, target: int, maxDoubles: int) -> int:res = 0while target > 1 and maxDoubles > 0:if target & 1 == 1:target -= 1else:target //= 2maxDoubles -= 1res += 1return res + target - 1
关键字:专业网站有哪些平台_商城网站有哪些_单页网站怎么优化_如何在网上推广自己

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: