Determine the Minimum Sum of a k-avoiding Array - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, k = 4
Output: 8
💡 Note: The k-avoiding array [1,2,5] has the minimum sum. We skip 3 and 4 because 1+3=4 and 2+2=4 (but we need distinct elements, so we avoid the pair (1,3)).
Example 2 — Large k
$ Input: n = 2, k = 6
Output: 3
💡 Note: Since k=6 is large, we can take the first n=2 numbers: [1,2]. Their sum is 1+2=3, and 1+2≠6 so it's k-avoiding.
Example 3 — Small k
$ Input: n = 2, k = 3
Output: 4
💡 Note: We cannot use [1,2] because 1+2=3=k. So we take [1,3] with sum 4, avoiding the forbidden pair.

Constraints

  • 1 ≤ n, k ≤ 50

Visualization

Tap to expand
Minimum Sum of a k-avoiding Array INPUT Build array of length n avoiding pairs summing to k ? ? ? Need 3 distinct positive integers Forbidden Pairs (sum=4): (1,3) (2,2) Input Values n = 3 k = 4 ALGORITHM STEPS 1 Start with i=1 Begin from smallest positive int 2 Check if valid Is (k-i) already in array? 3 Add or Skip Add if valid, skip if conflict 4 Repeat until n elements Continue greedy selection Greedy Trace i=1: add 1 (4-1=3 not in arr) i=2: add 2 (4-2=2 != 2, OK) i=3: SKIP (4-3=1 in arr!) FINAL RESULT k-avoiding Array: 1 2 5 After i=3 skip, continue: i=4: SKIP (4-4=0, edge case) i=5: add 5 (4-5=-1, OK) Sum = 1 + 2 + 5 = 8 Output 8 [OK] No pairs sum to 4 Key Insight: For k-avoiding array, we can only pick ONE number from each conflicting pair (i, k-i). Greedy approach: Always pick the smaller number to minimize sum. For k=4: pick 1 (not 3), pick 2 (self-pair). TutorialsPoint - Determine the Minimum Sum of a k-avoiding Array | Greedy Construction Approach
Asked in
Google 15 Meta 12 Amazon 8
3.2K Views
Medium Frequency
~15 min Avg. Time
145 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen