Amazon interview question

Question based on stacks and then dynamic programming