52.2k views
5 votes
Letm1, m2,···mnbe distinct numbers on the number line, in the increasing order. Your goalis to color all of them blue. You have magical blue pens with the following property: Whenyou place the pen at co-ordinate x, all the points in the range [x - 5, x + 5] turn blue. Apen can be used only once. Give an algorithm to color all the points using as few pens aspossible. Prove the correctness of the algorithm and derive the runtime.

User Amra
by
4.8k points

1 Answer

3 votes

Answer:

Following are the algorithm to this question:

y = 0 // initialize variable y that assigns the value 0

p = 1 // initialize value 1 in the variable p which also known as starting position

init num = 1//define variable num that assign value 1

for j = 1 to n: //defining loop

y = m[j] - m[p]

if (y > 10) //defining if block

num++; //increment num variable

p=i; //holding loop value in p variable

y= 0//assign value 0 in y variable

Step-by-step explanation:

Following are the runtime analysis of the above-given algorithm:

The above-provided algorithm is greedy, but if it doesn't exceed the scope, it operates by greedily choosing its next object. Therefore the algorithm selects the fewest number of pens.

Running time:

This algorithm merely iterates once over all the points. The run-time is therefore O(n).

User Paradisiak
by
5.0k points