Find Score of an Array After Marking All Elements - Problem

You are given an array nums consisting of positive integers.

Starting with score = 0, apply the following algorithm:

  1. Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.
  2. Add the value of the chosen integer to score.
  3. Mark the chosen element and its two adjacent elements if they exist.
  4. Repeat until all the array elements are marked.

Return the score you get after applying the above algorithm.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,4,5,2]
Output: 7
💡 Note: Choose 1 (smallest), mark indices 0,1,2 → score=1. Choose 2 (at index 5), mark indices 4,5 → score=3. Choose 4 (at index 3), mark index 3 → score=7. All elements marked.
Example 2 — All Same Values
$ Input: nums = [2,2,2,2]
Output: 4
💡 Note: Choose first 2 (index 0), mark indices 0,1 → score=2. Choose 2 (index 2), mark indices 1,2,3 → score=4. All marked.
Example 3 — Single Element
$ Input: nums = [5]
Output: 5
💡 Note: Only one element, choose it → score=5.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Find Score After Marking Elements INPUT nums array: 0 1 2 3 4 5 2 1 3 4 5 2 Initial State: score = 0 marked = [F,F,F,F,F,F] Processing Order: (value, index) pairs (1,1) (2,0) (2,5) (3,2) (4,3) (5,4) Sort by value, then index Use min-heap or sorting ALGORITHM STEPS 1 Pick (1, idx=1) score += 1 = 1 Mark idx: 0,1,2 2 1 3 4 5 2 2 Pick (4, idx=3) score += 4 = 5 Mark idx: 2,3,4 2 1 3 4 5 2 3 Pick (2, idx=5) score += 2 = 7 Mark idx: 4,5 2 1 3 4 5 2 4 All Marked! Final score = 7 Selected Marked FINAL RESULT Output: 7 Score Breakdown: 1 (idx=1) : +1 4 (idx=3) : +4 2 (idx=5) : +2 Total : 7 Status: OK All elements marked Time: O(n log n) Space: O(n) Key Insight: Use a min-heap or sorted list of (value, index) pairs to always pick the smallest unmarked element. When selecting an element, mark it and its adjacent indices. Skip already-marked elements in the heap. This greedy approach ensures we always add the minimum available value to maximize our selections. TutorialsPoint - Find Score of an Array After Marking All Elements | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen