We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Apply Operations to Make Sum of Array Greater Than or Equal to k

Difficulty: Medium


Problem Description

You are given a positive integer k. Initially, you have an array nums = [1]. You can perform any of the following operations on the array any number of times (possibly zero):

  • Choose any element in the array and increase its value by 1.
  • Duplicate any element in the array and add it to the end of the array.

Return the minimum number of operations required to make the sum of elements of the final array greater than or equal to k.


Key Insights

  • The initial array starts with a single element, 1.
  • The sum can be increased either by incrementing existing elements or by duplicating them, which can exponentially increase the sum.
  • The goal is to reach or exceed the target sum k using the least number of operations.
  • A greedy approach can be applied: always consider the best option (either incrementing or duplicating) at each step.

Space and Time Complexity

Time Complexity: O(log k) - The number of duplications can grow exponentially, leading to a logarithmic relationship with respect to k. Space Complexity: O(1) - We only need a few variables to keep track of the current sum and the number of operations.


Solution

The algorithm starts with the initial sum of the array (which is 1) and iteratively decides whether to increment the current maximum value or duplicate it based on which operation minimizes the number of total operations to reach or exceed k. Each increment increases the sum linearly, while duplication can exponentially increase it, making it a preferable option when the sum is close to k.


Code Solutions

def min_operations(k):
    current_sum = 1
    operations = 0
    
    while current_sum < k:
        if current_sum * 2 <= k:
            # Duplicate the current sum
            current_sum *= 2
            operations += 1
        else:
            # Increment to reach at least k
            operations += (k - current_sum)
            current_sum = k  # We can consider it reached
            
    return operations
← Back to All Questions