Get Minimum Squares
Given a number N, write a program to print the minimum number of squares that sums to N.
N = 41
Minimum number of squares needed: 2
Explanation with example
We can think similar way as the coin change problem (refer to my article on coin change). We can start with the greedy approach and can see whether it works or not.
So, a greedy approach can be
First thing is to find whether we will be able to find answers for any number N. Is it possible to find squares that will sum up to N. Yes, we will be able to find for any number N because 1 is itself a square and we can get any number by summing 1?
Since we are to find the minimum number of squares it's apparent that we should pick the square with the maximum value closest to N and keep trying with that until the remaining sum is less the square. Then on course, we keep choosing the next best one. So, the algorithm would be like.
1) Let, count=0 to count minimum number of squares to sum
2) Pick up square x closest to N
3) While N≥x
4) if N=0
Go to Step 7
5) Pick up the next best square value <x & closest to N .assign it to x
6) Go to Step 2
7) End. count is the minimum number of squares needed to sum up.
Let's see whether the above greedy algorithm leads to the desired result or not.
N = 41
The square value closest to 41 is 36
count = 1, N = 5
Next best square value is 4
count = 2, N = 1
Next best square value is 1
count = 3, N = 0
So, minimum number of squares needed is 3
But is it really minimum?
If we choose 25 and 16, that sums up to 41 and we need only two squares.
That's the minimum, not 3.
So, greedy does not work as the local optimum choices doesn't make
global optimum choice. Hence, we need dynamic programing.