2530 Maximal Score After Applying Operations

Problem Statement

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

Instructions

  • 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.

For the whole problem statement, please refer here.

Plans

  • Use a max-heap to efficiently retrieve the maximum element in nums for every operation.

  • Perform exactly k operations:

    • In each operation, pop (remove) the maximum element from the heap.

    • Increase the score by the popped element.

    • Compute the new value after applying the ceiling division by 3 and push it back to the heap.

  • Return the final score after completing k operations.

Solution

from typing import List
import heapq
import math

class Solution:
    def maxKelements(self, nums: List[int], k: int) -> int:
        # Convert nums into a max heap by negating the values
        max_heap = [-num for num in nums]

        # Convert the list into a max heap
        heapq.heapify(max_heap)

        score = 0
        for _ in range(k):
            # Get the maximum element (remember to negate back)
            max_e = -heapq.heappop(max_heap)
            # Update the score
            score += max_e  
            
            # Calculate the new value after using the operation
            new_e = math.ceil(max_e / 3)
            # Push the new value back to the heap
            heapq.heappush(max_heap, -new_e)  
            
        return score

Explanation

  1. Max-Heap Initialization

    • Sice Python's heapq implements a min-heap, negate the elements of nums to simulate a max-heap. This allows us to always retrieve the larget element easily.

  2. Score Calculation

    • Initialize the score to 0.

    • Perform the k operations in each iteration:

      • Pop the maximum element from the heap and negate it back to get the original value.

      • Add the popped element to the score.

      • Compute the new value after applying the ceiling division by333.

  3. Inserting New Value

    • After calculating the new value, push it back to the max-heap by negating it.

  4. Return the Final Score

    • After completing k operations, return the final score which holds the maximum possible score after applying exactly k operations.

Last updated