Find Score of an Array After Marking All Elements — LeetCode 2593 Python Solution
- Problem
- #2593
- Pattern
- 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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n), where n is the length of the array auxiliary |
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
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 \times \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.