forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEgonD3V.py
More file actions
89 lines (71 loc) ยท 2.98 KB
/
EgonD3V.py
File metadata and controls
89 lines (71 loc) ยท 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from typing import List
from unittest import TestCase, main
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
return self.solve_divide_and_conquer(nums)
"""
Runtime: 548 ms (Beats 38.42%)
Time Complexity: O(n)
- nums๋ฅผ ์กฐํํ๋๋ฐ O(n)
- max_sum์ ๊ฐฑ์ ํ๋๋ฐ 2๊ฐ ํญ์ ๋ํ max์ฐ์ฐ์ O(2)
- max_subarray_sum์ ๊ฐฑ์ ํ๋๋ฐ 2๊ฐ ํญ์ ๋ํ max ์ฐ์ฐ์ O(2)
> O(n) * (O(2) + O(2)) = O(4 * n) ~= O(n)
Memory: 30.96 MB (Beats 74.82%)
Space Complexity: O(1)
> ์ ์ํ ๋ณ์, ์ค์ํ ๋ณ์ ํ๋ ์ฉ๋ง ์ฌ์ฉํ์ผ๋ฏ๋ก O(1)
"""
def solve_kadane(self, nums: List[int]) -> int:
max_subarray_sum, result = 0, float('-inf')
for num in nums:
max_subarray_sum = max(num, max_subarray_sum + num)
result = max(max_subarray_sum, result)
return result
"""
Runtime: 732 ms (Beats 5.04%)
Time Complexity: O(n * log n)
- max_prefix_sum์์ deepcopy์ O(n), ๊ณ์ฐ์ O(n)
- max_suffix_sum์์ deepcopy์ O(n), ๊ณ์ฐ์ O(n)
- divide_and_sum์์ ์ฌ๊ท ํธ์ถ depth๊ฐ log n, ํธ์ถ ๊ฒฐ๊ณผ์ ์ต๋ ๊ฐฏ์๋ n์ด๋ฏ๋ก, ์ผ๋ฐ์ ์ธ divide and conquer์ ์๊ฐ๋ณต์ก๋์ ๋์ผํ O(n * log n)
> 2 * O(n) + 2 * O(n) + O(n * log n) ~= O(n * log n)
Memory: 68.75 MB (Beats 20.29%)
Space Complexity: O(n)
- max_prefix_sum์์ O(n)
- max_suffix_sum์์ O(n)
> O(n) + O(n) = 2 * O(n) ~= O(n)
"""
def solve_divide_and_conquer(self, nums: List[int]) -> int:
max_prefix_sum = nums[::]
for i in range(1, len(nums)):
max_prefix_sum[i] = max(max_prefix_sum[i], max_prefix_sum[i - 1] + nums[i])
max_suffix_sum = nums[::]
for i in range(len(nums) - 2, -1, -1):
max_suffix_sum[i] = max(max_suffix_sum[i], max_suffix_sum[i + 1] + nums[i])
def divide_and_sum(nums: List[int], left: int, right: int) -> int:
if left == right:
return nums[left]
mid = (left + right) // 2
return max(
divide_and_sum(nums, left, mid),
max_prefix_sum[mid] + max_suffix_sum[mid + 1],
divide_and_sum(nums, mid + 1, right)
)
return divide_and_sum(nums, 0, len(nums) - 1)
class _LeetCodeTestCases(TestCase):
def test_1(self):
nums = [-2,1,-3,4,-1,2,1,-5,4]
output = 6
self.assertEqual(Solution.maxSubArray(Solution(), nums), output)
def test_2(self):
nums = [1]
output = 1
self.assertEqual(Solution.maxSubArray(Solution(), nums), output)
def test_3(self):
nums = [5,4,-1,7,8]
output = 23
self.assertEqual(Solution.maxSubArray(Solution(), nums), output)
def test_4(self):
nums = [-4, -3, -2, -1]
output = -1
self.assertEqual(Solution.maxSubArray(Solution(), nums), output)
if __name__ == '__main__':
main()