Maximal Score After Applying K Operations - Problem

You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0.

In one operation:

  • choose an index i such that 0 <= i < nums.length,
  • increase your score by nums[i], and
  • replace nums[i] with ceil(nums[i] / 3).

Return the maximum possible score you can attain after applying exactly k operations.

The ceiling function ceil(val) is the least integer greater than or equal to val.

Input & Output

Example 1 — Basic Case
$ Input: nums = [10,10,10,10,10], k = 5
Output: 50
💡 Note: Pick index 0: score=10, nums=[4,10,10,10,10]. Pick index 1: score=20, nums=[4,4,10,10,10]. Pick index 2: score=30, nums=[4,4,4,10,10]. Pick index 3: score=40, nums=[4,4,4,4,10]. Pick index 4: score=50, nums=[4,4,4,4,4]. Maximum score is 50.
Example 2 — Single Large Element
$ Input: nums = [1,10,3,3,3], k = 3
Output: 17
💡 Note: Pick 10: score=10, nums=[1,4,3,3,3]. Pick 4: score=14, nums=[1,2,3,3,3]. Pick any 3: score=17, nums=[1,2,1,3,3]. Best strategy is always pick the largest available.
Example 3 — Small Array
$ Input: nums = [5], k = 2
Output: 7
💡 Note: Pick 5: score=5, nums=[2]. Pick 2: score=7, nums=[1]. Only one element, so must pick from it k times.

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ 2 × 103

Visualization

Tap to expand
Maximal Score After K Operations INPUT nums array (5 elements) 10 i=0 10 i=1 10 i=2 10 i=3 10 i=4 k = 5 operations Initial Max Heap 10 10 10 10 10 ALGORITHM STEPS 1 Build Max Heap Insert all nums into heap 2 Extract Maximum Pop largest element 3 Add to Score score += max value 4 Push ceil(max/3) Repeat k times Operations Trace: Op Pop Push Score 1 10 ceil(10/3)=4 10 2 10 ceil(10/3)=4 20 3 10 ceil(10/3)=4 30 4 10 ceil(10/3)=4 40 5 10 ceil(10/3)=4 50 FINAL RESULT After 5 operations: Maximum Score 50 Score Breakdown: 10 + 10 + 10 + 10 + 10 = 50 (All 10s picked first) Final Heap State: 4 4 4 4 4 [4, 4, 4, 4, 4] OK - Output: 50 Key Insight: Greedy approach works because we always want the maximum available value. Max Heap provides O(log n) extraction and insertion. Total time: O(k log n). After taking a value, ceil(val/3) ensures the element decreases but remains usable. TutorialsPoint - Maximal Score After Applying K Operations | Greedy with Max Heap
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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