LeetCode Notes: Weekly Contest 229 Contest Record

0. Summary after the game

This week’s game was on my knees as a whole. Both games were unsuccessful and dying. Yesterday’s game could still be attributed to the wrong question. This time the game really didn’t have to be washed. After the third question was overtime There is no better idea. There is no feasible idea for the fourth question at all. After the solution that I thought of was realized, it was found that there were systemic bugs. It was simply...

Sure enough, arrogance is the original sin. I am so weak, and I still brag about others, I stand up with the flag and stand on my face, alas...

1. Topic One

The link to the question given for question one is as follows:

1. Problem-solving ideas

This question is not difficult, just alternately form a new string according to the meaning of the question.

2. Code implementation

The python code is given as follows:

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        n, m = len(word1), len(word2)
        i, j = 0, 0
        res = ""
        while i<n and j<m:
            res += word1[i] + word2[j]
            i += 1
            j += 1
        if i < n:
            res += word1[i:]
        if j < m:
            res += word2[j:]
        return res

After submitting the code evaluation, it took 56ms and took up 14.2MB of memory.

The most current code implementation takes 28ms, but after looking at the implementation ideas, they are exactly the same, so I won’t expand too much.

2. Topic 2

The link to the test questions for topic two is as follows:

1. Problem-solving ideas

This problem was solved by force using a brute force algorithm during the competition, but the code is not elegant enough. After the game, I looked at it again. In fact, the algorithm complexity can be reduced to O (N) O(N).O ( N )

First, let's calculate the cost of all moving to the first position.

Then, we assume that all the known move to the iiThe answer for i positions issi s_isi, The inspection is all moved to the i + 1 i+1i+The cost of 1 hour is obviously:

si + 1 = si + ci - (tot - ci) s_ {i + 1} = s_ {i} + c_ {i} - (tot - c_ {i}) si+1=si+ci( t o tci)

Among them, ci c_iciTo iiThe number of balls contained up to i positions,tot tott o t is the total number of balls.

Therefore, through the idea of ​​mathematical induction, we can find that O (N) O(N)Obtain solutions at all positions in the case of O ( N ) algorithm complexity.

2. Code implementation

The python code is given as follows:

class Solution:
    def minOperations(self, boxes: str) -> List[int]:
        boxes = [int(x) for x in boxes]
        n = len(boxes)
        cumsum = list(accumulate(boxes))
        res = [0 for _ in range(n)]
        s = 0
        for i in range(n):
            s += i*boxes[i]
        res[0] = s
        for i in range(1, n):
            s += cumsum[i-1] - (cumsum[-1] - cumsum[i-1])
            res[i] = s
        return res

Submit the code for evaluation and get: It takes 100ms and takes up 14.4MB of memory.

Implemented for the current best code.

3. Topic Three

The link to the test questions for topic three is as follows:

1. Problem-solving ideas

During the competition, I couldn’t solve this problem because of overtime. After the game, I looked at other people’s solutions, and then I broke my three views, because his algorithm implementation is exactly the same as mine, that is, one line of code and one line more than mine. Clean up the cached code, and then avoid the timeout problem...

Hehe, this question is really stupid...

It’s nothing complicated. If you solve it violently, it is dynamic programming. Let’s see if there are any better ideas for solving problems...

2. Code implementation

The python code is given as follows:

class Solution:
    def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
        n, m = len(nums), len(multipliers)
        
        @lru_cache(None)
        def dp(i, j, k):
            if k == m:
                return 0
            return max(nums[i]*multipliers[k] + dp(i+1, j, k+1), nums[j]*multipliers[k] + dp(i, j-1, k+1))
        
        res = dp(0, n-1, 0)
        dp.cache_clear()
        return res

Submit code evaluation and get: It takes 8052ms and takes up 160.1MB of memory.

The current optimal code implementation takes 3336ms, and there is no difference in magnitude, but it has an efficiency improvement of nearly 3 times. Therefore, interested readers can study their ideas in the follow-up.

4. Topic Four

The link to the test question for question four is as follows:

1. Problem-solving ideas

This question did not have a good idea at all during the competition. The direct idea is to first concatenate and compare the positive and negative strings, and examine the related content of the common substrings before proceeding, but it is the boundary problem...

After the game, I was lost for a long time, and after looking at the answer today, I found that it was just a dynamic programming problem. It was basically the same as the previous one. Just use two sliding pointers to approach the center from both sides.

2. Code implementation

The python code is given as follows:

class Solution:
    def longestPalindrome(self, word1: str, word2: str) -> int:
        s = word1 + word2
        n, m = len(word1), len(word2)
        
        @lru_cache(None)
        def dp(i, j, s1, s2):
            if i >= n and not s1:
                return -10000
            if j < n and not s2:
                return -10000
            if i == j:
                return 1
            if i > j:
                return 0
            
            if s[i] == s[j]:
                return 2 + dp(i+1, j-1, True, True)
            else:
                return max(dp(i, j-1, s1, s2), dp(i+1, j, s1, s2))
            
        res = dp(0, n+m-1, False, False)
        dp.cache_clear()
        return max(res, 0)

After submitting the code for evaluation, it took 4356ms and occupied 432.9MB of memory.

The current optimal code implementation takes 2536ms. Interested readers can study it by themselves. I will not do more here for the time being...

Guess you like

Origin blog.csdn.net/codename_cys/article/details/114108081