forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make-array-non-decreasing-or-non-increasing.py
49 lines (40 loc) · 1.19 KB
/
make-array-non-decreasing-or-non-increasing.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
# Time: O(nlogn)
# Space: O(n)
import heapq
# greedy, heap
class Solution(object):
def convertArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def f(nums):
result = 0
max_heap = []
for x in nums:
if max_heap and x < -max_heap[0]:
result += -heapq.heappop(max_heap)-x
heapq.heappush(max_heap, -x)
heapq.heappush(max_heap, -x)
return result
return min(f(nums), f((x for x in reversed(nums))))
# Time: O(n^2)
# Space: O(n)
import collections
# dp
class Solution2(object):
def convertArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
vals = sorted(set(nums))
def f(nums):
dp = collections.defaultdict(int) # dp[i]: min(cnt(j) for j in vals if j <= i)
for x in nums:
prev = -1
for i in vals:
dp[i] = min(dp[i]+abs(i-x), dp[prev]) if prev != -1 else dp[i]+abs(i-x)
prev = i
return dp[vals[-1]]
return min(f(nums), f((x for x in reversed(nums))))