Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【每日一题】- 2020-09-03 - 机器人跳跃问题 #423

Closed
azl397985856 opened this issue Sep 3, 2020 · 2 comments
Closed

【每日一题】- 2020-09-03 - 机器人跳跃问题 #423

azl397985856 opened this issue Sep 3, 2020 · 2 comments

Comments

@azl397985856
Copy link
Owner

[编程题]机器人跳跃问题
时间限制:C/C++ 1秒,其他语言2秒

空间限制:C/C++ 32M,其他语言64M

机器人正在玩一个古老的基于DOS的游戏。游戏中有N+1座建筑——从0到N编号,从左到右排列。编号为0的建筑高度为0个单位,编号为i的建筑的高度为H(i)个单位。

起初, 机器人在编号为0的建筑处。每一步,它跳到下一个(右边)建筑。假设机器人在第k个建筑,且它现在的能量值是E, 下一步它将跳到第个k+1建筑。它将会得到或者失去正比于与H(k+1)与E之差的能量。如果 H(k+1) > E 那么机器人就失去 H(k+1) - E 的能量值,否则它将得到 E - H(k+1) 的能量值。

游戏目标是到达第个N建筑,在这个过程中,能量值不能为负数个单位。现在的问题是机器人以多少能量值开始游戏,才可以保证成功完成游戏?

输入描述:
第一行输入,表示一共有 N 组数据.

第二个是 N 个空格分隔的整数,H1, H2, H3, ..., Hn 代表建筑物的高度

输出描述:
输出一个单独的数表示完成游戏所需的最少单位的初始能量

输入例子1:
5
3 4 3 2 4

输出例子1:
4

输入例子2:
3
4 4 4

输出例子2:
4

输入例子3:
3
1 6 4

输出例子3:
3

地址:https://www.nowcoder.com/question/next?pid=16516564&qid=362295&tid=36905981

@azl397985856
Copy link
Owner Author

azl397985856 commented Sep 3, 2020

思路

从后往前思考。到达最后一级的能量最少是 0 。而由于:

next = pre + (pre - H[i])

因此:

pre = (next + H[i]) / 2

由于除以 2 可能会出现小数的情况,因此需要 ceil。

你可以:

pre = math.ceil((next + H[i]) / 2)

也可以:

pre = (next + H[i] + 1) // 2

// 是地板除,即向下取整

代码(Python)

n = input()
H = input().split(" ")
ans = 0
for i in range(len(H) - 1, -1, -1):
    ans = (ans + int(H[i]) + 1) // 2
print(ans)

复杂度分析

  • 时间复杂度:$O(N)$
  • 空间复杂度:$O(1)$

更多题解可以访问我的LeetCode题解仓库:https://github.com/azl397985856/leetcode 。 目前已经35K star啦。

关注公众号力扣加加,努力用清晰直白的语言还原解题思路,并且有大量图解,手把手教你识别套路,高效刷题。

@stale
Copy link

stale bot commented Nov 2, 2020

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant