-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_score.py
More file actions
28 lines (21 loc) · 753 Bytes
/
find_score.py
File metadata and controls
28 lines (21 loc) · 753 Bytes
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
import heapq
class Solution:
def findScore(self, nums):
min_heap = [(num, i) for i, num in enumerate(nums)]
heapq.heapify(min_heap)
n = len(nums)
states = [0] * n
total_score = 0
while min_heap:
curr_num, curr_idx = heapq.heappop(min_heap)
total_score += curr_num
states[curr_idx] = 1
neighbours = [curr_idx - 1, curr_idx + 1]
for neighbour in neighbours:
if 0 <= neighbour < n:
states[neighbour] = 1
while min_heap and states[min_heap[0][1]] == 1:
heapq.heappop(min_heap)
return total_score
# Time Complexity: O(n logn)
# Space Complexity: O(n)