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

Determine the Minimum Sum of a k-avoiding Array

Difficulty: Medium


Problem Description

You are given two integers, n and k. An array of distinct positive integers is called a k-avoiding array if there does not exist any pair of distinct elements that sum to k. Return the minimum possible sum of a k-avoiding array of length n.


Key Insights

  • The elements of the array must be distinct positive integers.
  • A k-avoiding array cannot contain pairs of numbers (x, y) such that x + y = k.
  • To minimize the sum, we should start from the smallest integers and skip any numbers that would create a forbidden pair.
  • The maximum value of n and k is 50, allowing for an efficient solution.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

To solve this problem, we can use a greedy approach. We start building the array by iterating through the smallest distinct positive integers and adding them to the array. If adding a number would create a pair that sums to k with any existing number in the array, we skip that number. This continues until we have n numbers.

The data structure used here is a simple list to store the k-avoiding integers. The algorithm ensures that we maintain distinct integers while checking for the condition of avoiding pairs that sum to k.


Code Solutions

def minimum_sum(n, k):
    result = []
    current = 1
    while len(result) < n:
        if k - current not in result:  # Check if the pair is not in the result
            result.append(current)
        current += 1
    return sum(result)

# Example usage
print(minimum_sum(5, 4))  # Output: 18
print(minimum_sum(2, 6))  # Output: 3
← Back to All Questions