일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- LeetCode
- Python Implementation
- 프로그래머스
- Generator
- data science
- 컴퓨터의 구조
- shiba
- Python Code
- Class
- 715. Range Module
- Python
- concurrency
- kaggle
- Protocol
- 30. Substring with Concatenation of All Words
- 43. Multiply Strings
- t1
- Regular Expression
- 운영체제
- Substring with Concatenation of All Words
- 109. Convert Sorted List to Binary Search Tree
- 밴픽
- Decorator
- 파이썬
- DWG
- attribute
- iterator
- Convert Sorted List to Binary Search Tree
- 315. Count of Smaller Numbers After Self
- 시바견
Archives
- Today
- Total
Scribbling
LeetCode: 410. Split Array Largest Sum 본문
DP Solution
Time complexity: O(M*N**2)
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
self.nums = nums
self.table = [0] * (len(nums)+1)
summed = 0
for i in range(len(nums)):
summed += nums[i]
self.table[i+1] = summed
self.dp = {}
return self.helper(0, len(nums)-1, m)
def helper(self, i, j, m):
if m == 1:
return self.table[j+1] - self.table[i]
if i == j:
return self.nums[i]
if (i, j, m) in self.dp:
return self.dp[(i, j, m)]
ret = int(1e9)
for k in range(i, j-m+2):
ret = min(ret, max(self.table[k+1]-self.table[i],
self.helper(k+1, j, m-1)))
self.dp[(i, j, m)] = ret
return ret
Binary Search Solution
Perhaps this is the most efficient solution. I guess the most difficult part of this solution is 'coming up with binary search'.
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def num_bins(val):
cnt = 0
summed, maxsum = 0, 0
for num in nums:
summed += num
if summed > val:
summed = num
cnt += 1
maxsum = max(maxsum, summed)
maxsum = max(maxsum, summed)
return cnt + 1, maxsum
ret = sum(nums)
left, right = max(nums), sum(nums)
while left <= right:
mid = (left + right) // 2
k, maxsum = num_bins(mid)
if k <= m:
ret = min(ret, mid)
right = mid - 1
else:
left = mid + 1
return ret
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 652. Find Duplicate Subtrees (0) | 2022.02.23 |
---|---|
LeetCode: 465. Optimal Account Balancing (0) | 2022.02.17 |
LeetCode: 315. Count of Smaller Numbers After Self (0) | 2022.02.10 |
LeetCode: 135. Candy (0) | 2022.02.03 |
LeetCode: 366. Find Leaves of Binary Tree (0) | 2022.02.02 |