First intuition is a greedy algorithm which takes the max element of the array and finds that index and we can compute the answer pretty straight forward from there. However, this results in TLE.
We can use a max heap to get the max element in O(logn) time. Since we are also given the nums array, we can use the built-in heapify algorithm to convert nums into a max heap in O(n) time instead of traditional O(nlogn) methods.
import heapq
classSolution:defmaxKelements(self, nums: List[int], k:int)->int: score =0for i inrange(len(nums)): nums[i]*=-1 heapq.heapify(nums)for _ inrange(k): x =-heapq.heappop(nums) score += x
heapq.heappush(nums,-ceil(x /3))return score
Note in Python there is only a min heap variant given by heapq, so we simply just negate the values.