Suppose we have an array nums containing size of n different cubes, they are placed horizontally. We have to make a pile of cubes vertically. The new cube should follow −
When we are making the vertical pile, we can only take cubes from left side or right side but not from the middle. We have to check whether we can pile them up or not.
So, if the input is like nums = [1,2,3,7,8], then the output will be True because we can take boxes from right to left to pile them up successfully.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding
from collections import deque def solve(nums): n = len(nums) d = deque(nums) flag = True prev = 0 while d: first = d last = d[-1] if prev != 0 and (first > prev or last > prev): flag = False break if first >= last: prev = d.popleft() else: prev = d.pop() if flag: return True else: return False nums = [1,2,3,7,8] print(solve(nums))