[Huawei OD Unified Exam B Paper | 100 points] Find the minimum number of steps (C++ Java JavaScript Python)

Online OJ

Users who have already purchased this column, please private message the blogger to open an account and brush up questions online! ! !

Online OJ: brush the questions immediately

Question bank column: 2023 Huawei OD machine test (A volume + B volume) (C++JavaJSPy)

topic description

Find the minimum number of steps from coordinate zero to coordinate point n, and only move 2 or 3 to the left or right along the abscissa axis at a time.

Note: The coordinate points of the route can be negative

enter description

coordinate point n

output description

Output the minimum number of steps to move from coordinate zero to coordinate point n

Remark

1 <= n <= 10^9

Example

enter

4

output

2

Moving from coordinate zero to 4 requires a minimum of two steps, that is, move to the right by 2, and then move to the right by 2

Code idea - dynamic programming

We can define an array dp, where dp[i] represents the minimum number of steps required to reach coordinate point i. Initially, dp[0] is 0, which means that no movement is required to reach the coordinate zero.

Then, we can calculate the value of dp[i] by iterating over the array dp. For each dp[i], we can choose to start from dp[i-2] or dp[i-3

Guess you like

Origin blog.csdn.net/shangyanaf/article/details/131749160