#2593

Find Score of an Array After Marking All Elements

Medium
ArrayHash TableSortingHeap (Priority Queue)SimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages sorting and a priority queue to efficiently find the smallest unmarked element while keeping track of marked elements. This reduces the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list of tuples containing each element and its index, then sort this list based on the element values.
  2. 2Step 2: Initialize a marked array and a score variable.
  3. 3Step 3: Iterate through the sorted list, marking elements and their neighbors while updating the score.
solution.py18 lines
1import heapq
2
3def findScore(nums):
4    n = len(nums)
5    indexed_nums = [(num, i) for i, num in enumerate(nums)]
6    indexed_nums.sort()
7    marked = [False] * n
8    score = 0
9    for num, i in indexed_nums:
10        if marked[i]:
11            continue
12        score += num
13        marked[i] = True
14        if i > 0:
15            marked[i - 1] = True
16        if i < n - 1:
17            marked[i + 1] = True
18    return score

Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the marked elements and indexed array.

  • 1Sorting helps efficiently identify the smallest unmarked element.
  • 2Using a marked array allows quick checks for already processed elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.