MediumNo. 2593
Find Score of an Array After Marking All Elements — LeetCode 2593 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Array, Hash Table, Sorting, Simulation, Heap (Priority Queue)
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an array nums consisting of positive integers. Starting with score = 0, apply the following algorithm: Choose the smallest integer of the array that is not marked.
Example
- Input
- nums = [2,1,3,4,5,2]
- Output
- 7
- Explanation
- We mark the elements as follows:
Python solution
class Solution:
def findScore(self, nums: List[int]) -> int:
n = len(nums)
vis = [False] * n
q = [(x, i) for i, x in enumerate(nums)]
heapify(q)
ans = 0
while q:
x, i = heappop(q)
ans += x
vis[i] = True
for j in (i - 1, i + 1):
if 0 <= j < n:
vis[j] = True
while q and vis[q[0][1]]:
heappop(q)
return ansComplexity
- Time
- O(n × log n)
- Space · auxiliary
- O(n)where n is the length of the array
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2593. Find Score of an Array After Marking All Elements is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 2357 | Make Array Zero by Subtracting Equal Amounts | Easy |
| 2402 | Meeting Rooms III | Hard |
| 0347 | Top K Frequent Elements | Medium |
| 0621 | Task Scheduler | Medium |
| 0632 | Smallest Range Covering Elements from K Lists | Hard |
| 0692 | Top K Frequent Words | Medium |
Frequently asked questions
- How hard is LeetCode 2593. Find Score of an Array After Marking All Elements?
LeetCode 2593. Find Score of an Array After Marking All Elements is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2593. Find Score of an Array After Marking All Elements?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 2593. Find Score of an Array After Marking All Elements?
The Python solution on this page uses O(n), where n is the length of the array auxiliary space.
- What topics does LeetCode 2593. Find Score of an Array After Marking All Elements cover?
LeetCode 2593. Find Score of an Array After Marking All Elements is tagged Array, Hash Table, Sorting, Simulation and Heap (Priority Queue) on LeetCode.