Skip to main content

1475.js

/** ------------------------------------------------------------------------------
*
* 1475. Final Prices With a Special Discount in a Shop
* Topics: Array, Monotonic Stack
* https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/?envType=daily-question&envId=2024-12-18
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} prices
* @return {number[]}
*/
var finalPrices = function (prices) {
let answer = []

for (let i = 0; i < prices.length; i++) {
const price = prices[i]
const salesIndex = prices.findIndex((v, index) => v <= price && index > i)

if (salesIndex === -1) {
answer.push(price)
} else {
answer.push(price - prices[salesIndex])
}
}

return answer
}

/**
* monotonic stack
*/
var finalPrices = function (prices) {
let stack = []
let answer = []

for (let i = 0; i < prices.length; i++) {
const price = prices[i]

while (stack.length > 0 && prices[stack[stack.length - 1]] >= price) {
console.log("while start")
console.log(stack)
const index = stack.pop()
answer[index] = prices[index] - price
console.log("while end: ", stack)
}

stack.push(i)
}

return answer
}

console.log(finalPrices([8, 4, 6, 2, 3]))