Maximum possible sum of squares of stack elements satisfying the given properties | Java program to implement the above approach ; Function to find the maximum sum of squares of stack elements ; Stores the sum ofsquares of stack elements ; Check if sum is valid ; Initialize all stack elements with 1 ; Stores the count the number of stack elements not equal to 1 ; Add the sum of squares of stack elements not equal to 1 ; Add 1 * 1 to res as the remaining stack elements are 1 ; Print the result ; Driver Code ; Function call
import java . io . * ; import java . util . * ; class GFG { public static void maxSumOfSquares ( int N , int S ) { int res = 0 ; if ( S < N S > 9 * N ) { System . out . println ( - 1 ) ; return ; } S = S - N ; int c = 0 ; while ( S > 0 ) { c ++ ; if ( S / 8 > 0 ) { res += 9 * 9 ; S -= 8 ; } else { res += ( S + 1 ) * ( S + 1 ) ; break ; } } res = res + ( N - c ) ; System . out . println ( res ) ; } public static void main ( String args [ ] ) { int N = 3 ; int S = 12 ; maxSumOfSquares ( N , S ) ; } }