#3028

Ant on the Boundary

newbie · 260 · lc easy +19 · verified · 74.3% accepted · 170 likes · top 85%

Description

An ant starts at a boundary. Given an array of non-zero integers nums, the ant reads elements in order:

- If nums[i] < 0, the ant moves left by -nums[i] units.

- If nums[i] > 0, the ant moves right by nums[i] units.

Return how many times the ant returns to the boundary.

Notes:
- The ant's position is checked only after each full move.
- Crossing the boundary mid-move does not count.

Example 1:

Input: nums = [2,3,-5]
Output: 1
Explanation: After the first step, the ant is 2 steps to the right of the boundary.
After the second step, the ant is 5 steps to the right of the boundary.
After the third step, the ant is on the boundary.
So the answer is 1.

Example 2:

Input: nums = [3,2,-3,-4]
Output: 0
Explanation: After the first step, the ant is 3 steps to the right of the boundary.
After the second step, the ant is 5 steps to the right of the boundary.
After the third step, the ant is 2 steps to the right of the boundary.
After the fourth step, the ant is 2 steps to the left of the boundary.
The ant never returned to the boundary, so the answer is 0.

Code

1
2
3