Maximum possible sum of squares of stack elements satisfying the given properties
Given two integers S and N, the task is to find the maximum possible sum of squares of N integers that can be placed in a stack such that the following properties are satisfied:
- The integer at the top of the stack should not be smaller than the element immediately below it.
- All stack elements should be in the range [1, 9].
- The Sum of stack elements should be exactly equal to S.
If it is impossible to obtain such an arrangement, print -1.
Input: S = 12, N = 3
Stack arrangement [9, 2, 1] generates the sum 12 (= S), thus, satisfying the properties.
Therefore, maximum possible sum of squares = 9 * 9 + 2 * 2 + 1 * 1= 81 + 4 + 1 = 86
Input: S = 11, N = 1
Approach: Follow the steps below to solve the problem:
- Check if S is valid, i.e. if it lies within the range [N, 9 * N].
- Initialize a variable, say res to store the maximum sum of squares of stack elements.
- The minimum value of an integer in the stack can be 1, so initialize all the stack elements with 1. Hence, deduct N from S.
- Now, check the number of integers having a value of more than 1. For this, add 8 (if it is possible) to the integers starting from the base of the stack and keep on adding it until S > 0.
- In the end, add S % 8 to the current integer and fill all remaining stack elements with 1.
- Finally, add the sum of squares of stack elements.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(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.