📌  相关文章
📜  求出K个数字,它们的总和等于N,并且其平方和最大

📅  最后修改于: 2021-04-23 15:43:13             🧑  作者: Mango

给定两个整数NK ,任务是找到K个数字( A 1 ,A 2 ,…,A K ),使得i = 1 K A i等于Ni = 1 K A i 2最大。
例子:

方法:想法是取1K – 1次,取N – K + 1次。这些数字的总和等于N,并且这些数字的平方和总是最大。对于任意两个非负数ab(a 2 + b 2 )始终小于1 +(a + b – 1) 2
下面是上述方法的实现:

C++
// C++ program to find K numbers
// with sum equal to N and the
// sum of their squares maximized
#include 
using namespace std;
 
// Function that prints the
// required K numbers
void printKNumbers(int N, int K)
{
    // Print 1, K-1 times
    for (int i = 0; i < K - 1; i++)
        cout << 1 << " ";
 
    // Print (N-K+1)
    cout << (N - K + 1);
}
 
// Driver Code
int main()
{
    int N = 10, K = 3;
 
    printKNumbers(N, K);
 
    return 0;
}


Java
// Java program to find K numbers
// with sum equal to N and the
// sum of their squares maximized
class GFG{
 
// Function that prints the
// required K numbers
static void printKNumbers(int N, int K)
{
    // Print 1, K-1 times
    for(int i = 0; i < K - 1; i++)
        System.out.print(1 + " ");
 
    // Print (N - K + 1)
    System.out.print(N - K + 1);
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 10, K = 3;
    printKNumbers(N, K);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program to find K numbers
# with a sum equal to N and the
# sum of their squares maximized
 
# Function that prints the
# required K numbers
def printKNumbers(N, K):
     
    # Print 1, K-1 times
    for i in range(K - 1):
        print(1, end = ' ')
     
    # Print (N-K+1)
    print(N - K + 1)
     
# Driver code
if __name__=='__main__':
     
    (N, K) = (10, 3)
     
    printKNumbers(N, K)
     
# This code is contributed by rutvik_56


C#
// C# program to find K numbers
// with sum equal to N and the
// sum of their squares maximized
using System;
     
class GFG{
 
// Function that prints the
// required K numbers
static void printKNumbers(int N, int K)
{
     
    // Print 1, K-1 times
    for(int i = 0; i < K - 1; i++)
        Console.Write(1 + " ");
 
    // Print (N - K + 1)
    Console.Write(N - K + 1);
}
 
// Driver code
public static void Main(String[] args)
{
    int N = 10, K = 3;
     
    printKNumbers(N, K);
}
}
 
// This code is contributed by shivanisinghss2110


Javascript


输出:
1 1 8

时间复杂度: O(K)
辅助空间: O(1)