检查是否可以将 N 个项目分成 K 组唯一大小
给定整数N和K ,任务是检查是否可以将N个数字分成K个组,使得所有K个组的大小不同,并且每个部分至少有一个数字。
例子:
Input: N = 5, K = 2
Output: Yes
Explanation: 5 numbers can be divided into 2 parts of different size. The possible size of the groups can be (1, 4) and (2, 3).
Input: N = 3, K = 3
Output: No
Explanation: 3 numbers cannot be divide into 3 groups of unique size.
处理方法:问题可以在以下观察的基础上解决。
To divide N numbers into K groups such that each group has at least one number and no two groups have same size:
- There should be at least K numbers. If N < K, then division is not possible.
- If N > K then the K groups will be at least of size 1, 2, 3, 4 . . . K . So N must be at least K*(K + 1)/2.
Therefore, the condition to be satisfied is N ≥ K*(K + 1)/2.
下面是上述方法的实现。
C++
// C++ code to implement above approach
#include
using namespace std;
// Function to check if it is possible
// to break N in K groups
void checkPartition(int N, int K)
{
// Invalid case
if (N < (K * (K + 1)) / 2) {
cout << "No";
}
else {
cout << "Yes";
}
}
// Driver code
int main()
{
int N = 6, K = 5;
checkPartition(N, K);
return 0;
}
C
// C code to implement above approach
#include
// Function to check if it is possible
// to break N in K groups
void checkPartition(int N, int K)
{
// Invalid case
if (N < (K * (K + 1)) / 2) {
printf("No");
}
else {
printf("Yes");
}
}
// Driver code
int main()
{
int N = 6, K = 5;
checkPartition(N, K);
return 0;
}
Java
// Java code to implement above approach
import java.io.*;
class GFG {
// Function to check if it is possible
// to break N in K groups
public static void checkPartition(int N, int K)
{
// Invalid case
if (N < (K * (K + 1) / 2)) {
System.out.print("No");
}
else {
System.out.print("Yes");
}
}
// Driver code
public static void main(String[] args)
{
int N = 6, K = 5;
checkPartition(N, K);
}
}
Python3
# Python code to implement above approach
def checkPartition(N, K):
# Invalid case
if (N < (K*(K + 1))//2):
print("No")
else:
print("Yes")
# Driver code
if __name__ == '__main__':
N = 6
K = 5
checkPartition(N, K)
C#
// C# code to implement above approach
using System;
class GFG {
// Function to check if it is possible
// to break N in K groups
public static void checkPartition(int N, int K)
{
// Invalid case
if (N < (K * (K + 1) / 2)) {
Console.Write("No");
}
else {
Console.Write("Yes");
}
}
// Driver code
public static void Main()
{
int N = 6, K = 5;
checkPartition(N, K);
}
}
// This code is contributed by saurabh_jaiswal.
Javascript
输出
No
时间复杂度: O(1)
辅助空间: O(1)。