Skip to main content
Back to problems
#2829
Medium Algorithms

Determine the minimum sum of a k avoiding array

Math Greedy
60.5% acceptance
Feb 25, 2026
344
13
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.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_sum(n: i32, k: i32) -> i32 {
    // Pick 1..floor(k/2) first, then k, k+1, ...
    let m = n.min(k / 2) as i64;
    let remaining = n as i64 - m;
    let sum_first = m * (m + 1) / 2;
    let start = k as i64;
    let sum_rest = remaining * start + remaining * (remaining - 1) / 2;
    (sum_first + sum_rest) as i32
  }
}