Greedy Algorithms8 sections · 316 units
Open in Course

Create Maximum - Max from One Array

Monotonic stack selection

To get the maximum number of length mm from an array of length nn:

Use a monotonic decreasing stack. For each digit, while the stack is not empty, the top is smaller, and you have enough remaining digits to fill mm slots, pop the stack.

Push the current digit if the stack size is less than mm.

function maxFromOne(nums, m)
 stack := []
 drop := length - m
 for d in nums
 while stack not empty and stack.top < d and drop > 0
 stack.pop()
 drop := drop - 1
 if stack.size < m then
 stack.push(d)
 return stack