LeetCode: Minimum Deletion Cost To Avoid Repeating Letters Solution
Approach
Update the latest local max to calculate the right min
Implementation
1function Stack() {2 const stack = []34 this.push = function (el) {5 stack.push(el)6 }78 this.pop = function () {9 return stack.pop()10 }1112 this.peek = function () {13 return stack[stack.length - 1]14 }1516 this.isEmpty = function () {17 return stack.length === 018 }19}2021/**22 * @param {string} s23 * @param {number[]} cost24 * @return {number}25 */26var minCost = function (s, cost) {27 let res = 0,28 prev = 029 for (let i = 1; i < s.length; i++) {30 if (s[i] === s[i - 1]) {31 res += Math.min(cost[prev], cost[i])32 if (cost[i] > cost[prev]) {33 prev = i34 }35 } else {36 prev = i37 }38 }39 return res40}4142var minCost = function (s, cost) {43 const stack = new Stack()44 let res = 045 for (let i = 0; i < s.length; i++) {46 if (s[stack.peek()] !== s[i]) {47 stack.push(i)48 continue49 }5051 res += Math.min(cost[stack.peek()], cost[i])52 if (cost[i] > cost[stack.peek()]) {53 stack.pop()54 stack.push(i)55 }56 }57 return res58}
Comments
Loading comments...
Tags
leetcode
greedy
stack
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: The K Weakest Rows In A Matrix
Feb 16, 2021
Previous Post
LeetCode: Letter Case Permutation
Feb 16, 2021