๐ 1962.ย Remove Stones to Minimize the Total
-
1962.ย Remove Stones to Minimize the Total
Remove Stones to Minimize the Total - LeetCode
piles๋ผ๋ ์คํค์ ๋ชจ์๋ ๋ฆฌ์คํธ๊ฐ ์ฃผ์ด์ง๊ณ
k๋ผ๋ int๊ฐ ์ฃผ์ด์ ธ์ k๋งํผ piles ์คํค๋ค์ ๋บ ์ ์๋ค. ์๋ฅผ๋ค์ด
Input: piles = [5,4,9], k = 2
Output: 12
Explanation:ย Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are [5,4,5].
- Apply the operation on pile 0. The resulting piles are [3,4,5].
The total number of stones in [3,4,5] is 12.piles = [5,4,9] ์ฌ๊ธฐ์ 9๋ฅผ โ 9 - floor(piles[i] / 2) ์ด๋ ๊ฒ ํ ์ ์๋ค.
๋ฌธ์ ๋ that you can apply the operation on theย same pile more than once.
ํ๋์ ์คํค์ ์ฌ๋ฌ ์์ ์ ํ ์ ์๋ค๋ ๊ฑฐ๋ค ๊ทธ๋์ ์ ๋ ฌํ๋ค์ ์ ์ผ ํฐ๊ฐ๋ง ์์ ํด์ฃผ์ ํด์
์ฝ๋๋ฅผ ์งฐ๋ค
class Solution:
def minStoneSum(self, piles: List[int], k: int) -> int:
lst_piles = sorted(piles, reverse=True)
for i in range(0, k):
pile = lst_piles[0] // 2
lst_piles[0] -= pile
lst_piles = sorted(lst_piles, reverse=True)
return sum(lst_piles)๊ทผ๋ฐ ์ฌ๊ฑธ ํ์ ๋ฆฌ๋ฐํธ๊ฐ ๊ฑธ๋ฆฌ๋ค..
๊ทธ๋ด์ค ์์๋คโฆ n log n ์ธ๋ฐ n ๊ฐ์ด 9๋ง์ ๋๋๋ฉด ํ์๋ฆฌ๋ฐ์ด ๊ฑธ๋ฆฌ๋๋ผ
์ด์จ๊ฑด ๋งค๋ฒ ์์ ํ ๋ ํฐ ์๋ฅผ ๊ตฌํด์ผ ํ๋๋ฐ
๊ทธ๋ฌ๋ฉด ๊ฒฐ๊ตญ ์ด๋ค ์๊ฐ ํฌ๋๋ฅผ ์์์ผ ํจ
๊ทธ๋ฌ๋ฉด ํญ์ ํฐ์๊ฐ ๊ฐ์ฅ ๋จผ์ ์ค๋ ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฐพ์์ผ ํ๊ณ ๊ทธ๊ฒ heap๋ฉ๋ชจ๋ฆฌ์
์ด์ง๋ฐ์ดํฐํธ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ฉด ๋๋๋ฐ python์์๋ heap์ ์ญ์์ผ๋ก ์ ๋ฆฌํ๋๊ฑด ์์ด์
๋ค์ด์ค๋ ๋ฐ์ดํฐ ๊ฐ์ -๋ก ๋ณ๊ฒฝํด์ ์ ๋ ฌ
import heapq
from typing import List
class Solution:
def minStoneSum(self, piles: List[int], k: int) -> int:
heap = []
for item in piles:
heapq.heappush(heap, -item)
for _ in range(k):
pile = heapq.heappop(heap)
pile = pile * -1
pile -= pile//2
heapq.heappush(heap, -pile)
return -sum(heap)ํน์ดํ ์ ์
5//2 == 2 ์ธ๋ฐ
-5//2 == -3 ์ด๋ค.
์ด์ ์ฃผ์ํด์ ํ์ด์ผ ํ ๋ฏ