Skip to main content

๐Ÿš€ 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 ์ด๋‹ค.

    ์ด์  ์ฃผ์˜ํ•ด์„œ ํ’€์–ด์•ผ ํ•  ๋“ฏ