195k views
5 votes
There is an infinite array of integers numbered consecutively from 0. At each step, a pointer can move from index / to index i + j, or remain where it is. The value of i begins at 0. The value of j begins at 1 and at each step, Jincrements by 1. There is one known index that must be avoided. Determine the highest index that can be reached in a given number of steps.

Example
steps = 4
badElement = 6
The pointer is limited to 4 steps and should avoid the bad item 6.
• Scenario 1:
• In the first step, starts at 1. Move 1 unit to index 0+1=1 and j = 2.
• At step 2, move 2 units to index 1 + 2 = 3, and j = 3.
• At step 3, do not move. Otherwise, the pointer will move 3 units to the bad item 6. Now j = 4.
At step 4, move 4 units to item 3 + 4 = 7.
Scenario 2:
• At step 1, remain at index 0. Now j = 2.
• At step 2, move 2 units to index 0+2=2 and j = 3.
• At step 3, move 3 units to index 2+3= 5 and j = 4.
• At step 4, move 4 units to index 5 + 4 = 9.
• The maximum index that can be reached is 9.
Function Description
Complete

User Johnson
by
7.8k points

1 Answer

4 votes

Final answer:

To determine the highest index that can be reached in a given number of steps while avoiding a specific index, you need to consider the pattern of the pointer's movements. The pointer starts at index 0 and can move from index i to index i + j or remain at the current index. In each step, j increments by 1. To avoid the bad index, you need to ensure that the pointer does not move j units when it is at a step where i + j equals the bad index.

Step-by-step explanation:

To determine the highest index that can be reached in a given number of steps while avoiding a specific index, you need to consider the pattern of the pointer's movements. The pointer starts at index 0 and can move from index i to index i + j or remain at the current index. In each step, j increments by 1. To avoid the bad index, you need to ensure that the pointer does not move j units when it is at a step where i + j equals the bad index.

Here's an approach you can follow:

  1. Initialize i to 0 and j to 1.
  2. Repeat the following steps for the given number of steps:
    • If i + j is equal to the bad index, do not move the pointer.
    • Otherwise, move the pointer from index i to index i + j.
    • Increase j by 1.
  3. The highest index that can be reached is the value of i after the given number of steps.

Applying this approach to the given example, with steps = 4 and badElement = 6, the highest index that can be reached is 9.

User Maarten Derickx
by
8.8k points