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:
- Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.
- Add the value of the chosen integer to
score. - Mark the chosen element and its two adjacent elements if they exist.
- 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code