Amazon Interview Question

Question based on stacks and then dynamic programming