Skip to content

Commit 394f06c

Browse files
committed
feat: add prev week solutions
1 parent bff76a0 commit 394f06c

2 files changed

Lines changed: 80 additions & 0 deletions

File tree

decode-ways/kangdaia.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def numDecodings(self, s: str) -> int:
3+
"""1에서 26까지 숫자를 알파벳으로 치환할 수 있을때,
4+
주어진 숫자 문자열이 어떤 알파벳으로 치환 될 수 있는지 방법의 수를 찾는 함수
5+
6+
방법:
7+
1. 경우의 수를 찾는 경우는 대부분 DP..?
8+
- 케이스가 명확함.
9+
현 위치의 숫자가 0이 아닌 경우, 해당 자리가 앞 숫자와 별개로 1~9 사이의 숫자를 선택할 수 있다.
10+
만약 앞의 경우를 포함해서 숫자가 10에서 26사이면 앞의 경우를 포함해서 경우의 숫자를 생각해야 함.
11+
다만 첫번째 숫자가 0이면 넘어가야 함.
12+
시간 복잡도: O(n) 공간 복잡도: O(n)
13+
14+
Args:
15+
s (str): 숫자로 이루어진 문자열
16+
17+
Returns:
18+
int: 문자열로 치환할 수 있는 알파벳 구성의 수
19+
"""
20+
dp = [0] * len(s)
21+
if s[0] != "0":
22+
dp[0] = 1
23+
for i in range(1, len(s)):
24+
if s[i] != "0":
25+
dp[i] += dp[i - 1]
26+
if "10" <= s[i - 1 : i + 1] <= "26":
27+
dp[i] += dp[i - 2] if i > 1 else 1
28+
return dp[-1]

maximum-subarray/kangdaia.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Solution:
2+
def maxSubArray(self, nums: list[int]) -> int:
3+
"""리스트의 이어진 문자열로 구성된 subarray중 최대 합을 찾는 함수
4+
5+
방법:
6+
1. brute force. 다만 O(n)으로 만들 수 없어 탈락!
7+
2. 전역 최대합과 로컬 최대 합을 분리해서 생각하기.
8+
연속된 문자열이기 때문에, 현재 값이 이전의 합보다 크면 앞의 값을 버리는 방식
9+
=> 시간 복잡도 O(n), 공간 복잡도 O(1)
10+
3. divide and conquer (Follow up)
11+
12+
Args:
13+
nums (list[int]): 정수 문자열
14+
15+
Returns:
16+
int: 최대 합
17+
"""
18+
max_sum = nums[0]
19+
local_sum = nums[0]
20+
for i in range(1, len(nums)):
21+
if local_sum < 0 and local_sum < nums[i]:
22+
local_sum = nums[i]
23+
else:
24+
local_sum += nums[i]
25+
max_sum = max(max_sum, local_sum)
26+
return max_sum
27+
28+
def maxSubArraySubtle(self, nums: list[int]) -> int:
29+
def divConq(left: int, right: int) -> int:
30+
if left == right:
31+
return nums[left]
32+
mid = (left + right) // 2
33+
34+
left_max = divConq(left, mid)
35+
right_max = divConq(mid + 1, right)
36+
37+
curr_sum = 0
38+
left_suffix_max = -float("inf")
39+
for idx in range(mid, left - 1, -1):
40+
curr_sum += nums[idx]
41+
left_suffix_max = max(left_suffix_max, curr_sum)
42+
43+
curr_sum = 0
44+
right_prefix_max = -float("inf")
45+
for idx in range(mid + 1, right + 1, 1):
46+
curr_sum += nums[idx]
47+
right_prefix_max = max(right_prefix_max, curr_sum)
48+
49+
cross = left_suffix_max + right_prefix_max
50+
return max(left_max, right_max, cross)
51+
52+
return divConq(0, len(nums) - 1)

0 commit comments

Comments
 (0)