๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 1578 - Minimum Deletion Cost to Avoid Repeating Letters (Medium)

by HandHand 2021. 3. 8.

๋ฌธ์ œ

LeetCode - 1578๋ฒˆ

ํ’€์ด ๊ณผ์ •

์—ฐ์†๋œ ๋ฌธ์ž์—ด์—์„œ ์ธ์ ‘ํ•œ ๊ฐ ์Œ์˜ ๋ฌธ์ž๊ฐ€ ์„œ๋กœ ๋‹ฌ๋ผ์•ผ ํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ๋ณด์ • ๊ฐ’์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋•Œ๋ฌธ์— ๊ฐ ๋ฌธ์ž๋ฅผ ํ•˜๋‚˜์”ฉ ์ˆœํšŒํ•˜๋ฉฐ ๊ฐ™์€ ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ์ธ์ ‘ํ•œ ๊ทธ๋ฃน๋“ค์„ ์ฐพ๊ณ , ์ด ๊ทธ๋ฃน ๋‚ด์—์„œ ๊ฐ€์žฅ ๋น„์šฉ์ด ํฐ ๋ฌธ์ž๋ฅผ ์ œ์™ธํ•˜๊ณ 
๋‹ค๋ฅธ ๋ชจ๋“  ๋ฌธ์ž๋“ค์„ ์„ ํƒํ•ด์„œ ์ œ๊ฑฐํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ € ๊ฐ™์€ ๊ฒฝ์šฐ ๊ฐ๊ฐ์˜ ๊ทธ๋ฃน์„ ๋จผ์ € ๋งŒ๋“ค๊ณ  ๋น„์šฉ์„ ๊ณ„์‚ฐํ–ˆ๋Š”๋ฐ, ์‚ฌ์‹ค ์ด๋Ÿด ํ•„์š”์—†์ด
๊ทธ๋ƒฅ ๊ฐ ๋ฌธ์ž๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ ์ธ์ ‘ํ•œ ๋ฌธ์ž๋“ค์ด ์„œ๋กœ ๊ฐ™์„ ๋•Œ ๊ทธ๋•Œ๊ทธ๋•Œ ๊ทธ๋ฃน์„ ๋งŒ๋“ค์–ด์„œ ๋น„์šฉ์„ ์ฒดํฌํ•ด์ค˜๋„ ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {string} s
 * @param {number[]} cost
 * @return {number}
 */
var minCost = function (s, cost) {
  const repeatingLetters = [];
  let isGroupExist = false;

  for (let i = 0, len = s.length; i < len - 1; i += 1) {
    if (s[i] == s[i + 1]) {
      if (isGroupExist) {
        repeatingLetters[repeatingLetters.length - 1].push(cost[i + 1]);
      } else {
        repeatingLetters.push([cost[i], cost[i + 1]]);
        isGroupExist = true;
      }
    } else {
      isGroupExist = false;
    }
  }

  const answer = repeatingLetters.reduce((acc, group) => {
    const sum = group.reduce((acc, cost) => acc + cost, 0);
    const max = Math.max(...group);

    return acc + (sum - max);
  }, 0);

  return answer;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 199 - Binary Tree Right Side View (Medium)  (0) 2021.04.05
LeetCode 344 - Reverse String (Easy)  (0) 2021.04.05
LeetCode 904 - Fruit Into Baskets (Medium)  (0) 2021.03.08
LeetCode 112 - Path Sum (Easy)  (0) 2021.03.04
LeetCode 63 - Unique Paths II (Medium)  (0) 2021.03.04

๐Ÿ’ฌ ๋Œ“๊ธ€