2829. Determine the Minimum Sum of a k-avoiding Array
Problem Statement
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
Intuition
Basically,
We want minimum sum
So start from 1 and go along
Store the alternate sum in hash set
Eg- k = 6
Take 1, Store 5 in map so you can skip that number ahead
Links
2829. Determine the Minimum Sum of a k-avoiding Array
Video Links
Approach 1:
class Solution {
public:
int minimumSum(int n, int k) {
int ans = 0;
unordered_map<int,int> mp;
int i=1;
while(n){
if(mp.find(i) == mp.end()){
ans += i;
mp[k-i] = 1;
n--;
}
i++;
}
return ans;
}
};
Approach 2:
Approach 3:
Approach 4:
Similar Problems
Last updated