Final Prices With a Special Discount in a Shop
EasyArrayStackMonotonic Stack
Solution
export function finalPrices(prices: number[]): number[] {
const answer = [...prices];
const stack: number[] = [];
prices.forEach((price, i) => {
while (0 < stack.length && price <= prices[stack[stack.length - 1]]) {
const prevIndex = stack.pop()!;
answer[prevIndex] -= price;
}
stack.push(i);
});
return answer;
}