파비의 매일매일 공부기록

2023.05.14 Today's Challenge 본문

Problem Solving/LeetCode

2023.05.14 Today's Challenge

fabichoi 2023. 5. 14. 23:45

https://leetcode.com/problems/maximize-score-after-n-operations/

 

Maximize Score After N Operations - LeetCode

Can you solve this real interview question? Maximize Score After N Operations - You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array. In the ith operation (1-indexed), you will: * Choose two elements,

leetcode.com

꽤 복잡한 문제였음

class Solution:
    def maxScore(self, nums: List[int]) -> int:
        max_states = 1 << len(nums)
        final_mask = max_states - 1

        dp = [0] * max_states

        for state in range(final_mask, -1, -1):
            if state == final_mask:
                dp[state] = 0
                continue
            
            numbers_taken = bin(state).count('1')
            pairs_formed = numbers_taken // 2

            if numbers_taken % 2:
                continue
            
            for fi in range(len(nums)):
                for si in range(fi+1, len(nums)):
                    if (state >> fi & 1) == 1 or (state >> si & 1) == 1:
                        continue
                    current_score = (pairs_formed+1) * math.gcd(nums[fi], nums[si])
                    state_after_picking_curr_pair = state | (1 << fi) | (1 << si)
                    remaining_score = dp[state_after_picking_curr_pair]
                    dp[state] = max(dp[state], current_score + remaining_score)
        
        return dp[0]
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.05.16 Today's Challenge  (0) 2023.05.16
2023.05.15 Today's Challenge  (1) 2023.05.15
2023.05.13 Today's Challenge  (1) 2023.05.13
2023.05.12 Today's Challenge  (0) 2023.05.12
2023.05.11 Today's Challenge  (0) 2023.05.11
Comments