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 ElementsInput: [2, 1, 3, 4, 5, 2]213452Step 1: Choose smallest (1)213452Score = 1, Mark neighbors of index 1Step 2: Choose next smallest unmarked (2)Continue until all elements markedFinal Score: 7Green=ChosenRed=MarkedBlue=Available
Understanding the Visualization
1
Input
Array of positive integers
2
Process
Repeatedly choose smallest unmarked, mark neighbors
3
Output
Sum of all chosen elements
Key Takeaway
🎯 Key Insight: Always choose the globally smallest unmarked element to maximize score
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