지난 공부기록/알고리즘 풀이

Python - Algorithm #34

hkl22 2024. 8. 7. 10:04

Python Algorithm

LeetCode

1374. Generate a String With Characters That Have Odd Counts

  • Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.
  • The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
  • Constraints
    • n 500
class Solution:
    def generateTheString(self, n: int) -> str:
        # n이 홀수일 때와 짝수일 때를 구분 지어 볼 것
        if n % 2 == 1:
            return "a" * n
        else:
            return "a" * (n-1) + "b"
class Solution:
    def generateTheString(self, n: int) -> str:
        for i in range(n):
            if n % 2 == 0:
                return "a" * (n-1) + "b"
            else:
                return "a" * n

2016. Maximum Difference Between Increasing Elements

  • Given a 0-indexed integer array [nums] of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].
  • Return the maximum difference. If no such i and j exists, return -1.
  • Constraints
    • n == nums.length
    • 2 n 1000
    • 1 nums[i] 10⁹
class Solution:
    def maximumDifference(self, nums: List[int]) -> int:
        # 2중 for문 사용
        answer = -1
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                # nums[i] < nums[j]일 때, max diff를 answer로 지정
                if nums[j] > nums[i]:
                    answer = max(answer, nums[j] - nums[i])
        return answer
class Solution:
    def maximumDifference(self, nums: List[int]) -> int:
        min_num = float("inf")
        answer = -1
        for num in nums:
            if num > min_num:
                answer = max(answer, num - min_num)
            else:
                min_num = num
        return answer
class Solution:
    def maximumDifference(self, nums: List[int]) -> int:
        answer = -1
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] < nums[j]:
                    answer = max(answer, (nums[j] - nums[i]))
        return answer

https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/

https://leetcode.com/problems/maximum-difference-between-increasing-elements/

'지난 공부기록 > 알고리즘 풀이' 카테고리의 다른 글

Python - Algorithm #36  (0) 2024.08.09
Python - Algorithm #35  (0) 2024.08.08
Python - Algorithm #33  (0) 2024.08.06
Python - Algorithm #32  (0) 2024.08.05
Python - Algorithm #31  (0) 2024.08.02