Find Score of an Array After Marking All Elements - Problem
You're given an array of positive integers, and your mission is to accumulate the highest possible score using a specific marking strategy!
The Algorithm:
- Start with
score = 0 - Find the smallest unmarked element in the array (if there's a tie, pick the one with the smallest index)
- Add this element's value to your score
- Mark this element AND its immediate neighbors (left and right adjacent elements, if they exist)
- Repeat until every element is marked
Your goal is to return the final score after applying this greedy marking algorithm.
Example: For array [2,1,3,4,5,2], you'd first pick 1 (smallest), mark positions 0,1,2, then pick 2 from position 5, and so on.
Input & Output
example_1.py โ Basic Array
$
Input:
[2,1,3,4,5,2]
โบ
Output:
7
๐ก Note:
Step 1: Pick 1 (smallest), score=1, mark indices [0,1,2]. Step 2: Pick 2 from index 5 (smallest remaining), score=3, mark indices [4,5]. Step 3: Pick 4 from index 3 (only remaining), score=7. Final score = 7.
example_2.py โ Small Array
$
Input:
[2,3,5,1,3,2]
โบ
Output:
5
๐ก Note:
Step 1: Pick 1 (index 3), score=1, mark [2,3,4]. Step 2: Pick 2 (index 0), score=3, mark [0,1]. Step 3: Pick 2 (index 5), score=5, mark [5]. All elements marked, final score = 5.
example_3.py โ Single Element
$
Input:
[1]
โบ
Output:
1
๐ก Note:
Only one element exists. Pick 1, add to score. No neighbors to mark. Final score = 1.
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 106
- All elements are positive integers
- Array can contain duplicate values
Visualization
Tap to expand
Understanding the Visualization
1
Survey Cave
Use a priority system (heap) to know which gem is smallest
2
Pick Smallest
Extract the smallest gem from your priority list
3
Seal Adjacent
Mark the gem's location and neighbors as sealed
4
Repeat Strategy
Continue until all gems are collected or sealed
Key Takeaway
๐ฏ Key Insight: Using a min-heap eliminates repeated scanning, reducing time from O(nยฒ) to O(n log n) while maintaining the greedy strategy of always picking the smallest available element.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code