forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-number-of-coins-for-fruits.py
70 lines (61 loc) · 1.62 KB
/
minimum-number-of-coins-for-fruits.py
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
# Time: O(n)
# Space: O(n)
import collections
# dp, mono deque
class Solution(object):
def minimumCoins(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
dp = [float("inf")]*(len(prices)+1)
dp[0] = 0
dq = collections.deque()
j = 0
for i in xrange(len(prices)):
while dq and dp[dq[-1]]+prices[dq[-1]] >= dp[i]+prices[i]:
dq.pop()
dq.append(i)
while j+(j+1) < i:
assert(len(dq) != 0)
if dq[0] == j:
dq.popleft()
j += 1
dp[i+1] = dp[dq[0]]+prices[dq[0]]
return dp[-1]
# Time: O(nlogn)
# Space: O(n)
# dp, sorted list
from sortedcontainers import SortedList
class Solution2(object):
def minimumCoins(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
dp = [float("inf")]*(len(prices)+1)
dp[0] = 0
sl = SortedList()
j = 0
for i in xrange(len(prices)):
sl.add((dp[i]+prices[i], i))
while j+(j+1) < i:
sl.remove(((dp[j]+prices[j], j)))
j += 1
dp[i+1] = sl[0][0]
return dp[-1]
# Time: O(n^2)
# Space: O(n)
# dp
class Solution3(object):
def minimumCoins(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
dp = [float("inf")]*(len(prices)+1)
dp[0] = 0
for i in xrange(len(prices)):
for j in xrange(i//2, i+1):
dp[i+1] = min(dp[i+1], dp[j]+prices[j])
return dp[-1]