Sponsored
Sponsored
By using a max-heap (priority queue), we can efficiently select the largest element from the array in each operation. This strategy maximizes the immediate score increase. Once an element is chosen, reinsert it into the heap with its updated value (after applying the ceiling function of division by 3) so it can be considered for future operations.
Time Complexity: O(k log n) - Each heap operation (insert/extract) takes O(log n) and we perform it 'k' times.
Space Complexity: O(n) - Due to the heap storage.
1import heapq
2import math
3
4def maxScore(nums, k):
5 # Using a max heap by inserting negative values
6 nums = [-num for num in nums]
7 heapq.heapify(nums)
8 score = 0
9
10 for _ in range(k):
11 # Extract maximum element
12 max_elem = -heapq.heappop(nums)
13 # Add to score
14 score += max_elem
15 # Calculate new value after operation
16 new_value = math.ceil(max_elem / 3)
17 # Insert back into heap
18 heapq.heappush(nums, -new_value)
19
20 return score
21
22# Example Usage
23nums = [1,10,3,3,3]
24k = 3
25print(maxScore(nums, k)) # Output: 17
The code uses a max-heap to choose the current largest value in each of the k
operations, updating the score and reinserting the modified element efficiently.
Sort the array in descending order and apply the operation greedily by always picking elements from the start of the array for maximum immediate score increase. Re-insert the updated elements after processing through their div-3 transformation.
Time Complexity: O(k log n) - Efficient dealing with priorities during extraction and insertion.
Space Complexity: O(n) - Storing elements in the priority queue for processing.
1using System;
2using System.Collections.Generic;
3
4public class MaxScoreClass
5{
public static int MaxScore(int[] nums, int k)
{
// Using PriorityQueue from C# Collections
var maxHeap = new PriorityQueue<int, int>(Comparer<int>.Create((x, y) => y - x));
foreach (var num in nums) maxHeap.Enqueue(num, num);
int score = 0;
for (int i = 0; i < k; ++i)
{
int maxElem = maxHeap.Dequeue();
score += maxElem;
maxHeap.Enqueue((int)Math.Ceiling(maxElem / 3.0), (int)Math.Ceiling(maxElem / 3.0));
}
return score;
}
public static void Main()
{
int[] nums = { 1, 10, 3, 3, 3 };
int k = 3;
Console.WriteLine(MaxScore(nums, k)); // Output: 17
}
}
The C# solution uses a priority queue to select and re-enqueue elements, optimized by a custom comparator to facilitate descending order behavior.