LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2829. Determine the Minimum Sum of a k-avoiding Array

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.

 

Example 1:

Input: n = 5, k = 4
Output: 18
Explanation: Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.

Example 2:

Input: n = 2, k = 6
Output: 3
Explanation: We can construct the array [1,2], which has a sum of 3.
It can be proven that there is no k-avoiding array with a sum less than 3.

 

Constraints:

  • 1 <= n, k <= 50

Solutions

Solution 1: Greedy + Simulation

Starting from the positive integer i = 1, we sequentially determine if i can be added to the array. If it can be added, we add i to the array, accumulate it to the answer, and then mark k - i as visited, indicating that k-i cannot be added to the array. We continue this process until the array's length reaches n.

The time complexity is O(n + k), and the space complexity is O(n + k). Where n is the length of the array.

PythonJavaC++GoTypeScriptRust
class Solution: def minimumSum(self, n: int, k: int) -> int: s, i = 0, 1 vis = set() for _ in range(n): while i in vis: i += 1 vis.add(k - i) s += i i += 1 return s(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !