Determine the Minimum Sum of a k-avoiding Array — LeetCode 2829 Python Solution
- Problem
- #2829
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- n = 5, k = 4
- Output
- 18
- Explanation
- Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
Python solution
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 sComplexity
| Measure | Complexity |
|---|---|
| Time | O(n + k) |
| Space | O(n + k) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array?
- LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array?
- The Python solution on this page runs in O(n + k).
- What is the space complexity of LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array?
- The Python solution on this page uses O(n + k) auxiliary space.
- What topics does LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array cover?
- LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array is tagged Greedy and Math on LeetCode.