Skip to content
Advertisement

Make a sequence an increasing sequence by adding a number multiple times

I have an array of numbers, now I want to make this as increasing sequence by adding a fixed number b. I want to find how many times the fixed number b is added to make my array as increasing sequence.

Here is the program which is working:

JavaScript

Example:

JavaScript

Explanation:

a[1] = 3 & a[2] = 3, so increment a[2] by B so a[2] = 3+2 = 5

Now a[2] = 5 & a[3]=2, so incremease a[3] by multiple of B so it is more than a[2], so a[3] = 2 + 2*2 = 6

So we have incremented 3 times, so the output is 3.

The time complexity of this program is O(N^2), but I was asked to reduce the time complexity of this program further. What is the better approach?

Advertisement

Answer

This should solve the problem in O(n):

JavaScript

The idea is to take the difference between adjacent numbers and evaluate how many Bs you need to add, which is the difference divided by B.

If adjacent numbers are equal, just add a single B.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement