Find K numbers with sum equal to N and sum of their squares maximized
Given two integers N and K, the task is to find K numbers(A1, A2, …, AK) such that ∑i=1KAi is equal to N and ∑i=1KAi2 is maximum.
Input: N = 3, K = 2
Output: 1 2
Explanation: The two numbers are 1 and 2 as their sum is equal to N and 12 + 22 is maximum.
Input: N = 10, K = 3
Output: 1 8 1
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Approach: The idea is to take number 1, K – 1 times and number N – K + 1 once. The sum of these numbers is equal to N and sum of squares of these numbers is always maximum. For any two non-negative numbers a and b, (a2 + b2) is always less than 1 + (a + b – 1)2.
Below is the implementation of the above approach:
1 1 8
Time Complexity: O(K)
Auxiliary Space: O(1)