Calculate the‍‌‍ ‍ ‍‌‍‌‍ minimum number of bricks

Question:

  • arr1 => denotes a tower.

  • The numbers in the array denotes the number of bricks used to build the tower.

  • We want the tower to be either ascending or descending, with the height difference between two consecutive elements being 1.

Calculate the minimum number of bricks needed.

Example:
arr1 = [1, 3, 5, 8] 
arr1(ascending): [5, 6, 7 , 8] 
Bricks needed: 4 + 3 + 2 = 9
Example:
arr1 = [3, 10, 9, 9, 4]
arr2(descending): [12, 11, 10, 9, 8]
Bricks needed:  9+1+1+4 = 15

Code:

arr = [1, 3, 5, 8] 

n=len(arr)

lmax=max(arr[i]+i for i in range(n))
res=sum(lmax-i-arr[i] for i in range(n))

print(res)

The output is 21 but it should be 9.

Asked By: meallhour

||

Answers:

The formula you use is a just a bit off. i should be subtracted (and added again in the second expression). So it should be:

lmax = max(arr[i] - i for i in range(n))
res = sum(lmax + i - arr[i] for i in range(n))

And then you need to compare which of the two possibilities (ascending, descending) needs the lesser bricks:

def solve(lst):
    def bricks_ascending(lst):
        lmax = max(height - i for i, height in enumerate(lst))
        return sum(lmax + i - height for i, height in enumerate(lst))

    return min(bricks_ascending(lst), bricks_ascending(lst[::-1]))
            

print(solve([1, 3, 5, 8]))  # 9
print(solve([3, 10, 9, 9, 4]))  # 15

Why subtract?

The idea is that i represents an ascending series of towers, starting at 0. It so represents an ascending series that has a minimal number of bricks. We need to see at which spot this minimal tower height needs most bricks to get to the actual height in the input array at that spot. Here is a visualisation of the first example input, together with that "i" ascending series:

enter image description here

At the left side we see that the greatest difference between the minimal ascending series and the actual height is at the last spot: 8 – 3 = 5. This 5 is arr[i] - i. That is the number of bricks that should be added to each minimal tower. We see the result of this addition in the right-most picture.

Answered By: trincot