279. Perfect Squares

Description

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Constraints

  • 1 <= n <= 104

Approach

  • Binarysearch

  • GeeksforGeeks

  • ProgramCreek

  • YouTube

Examples

Input: n = 12

Output: 3

Explanation: 12 = 4 + 4 + 4.

Solutions

/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public int numSquares(int n) {
        if(n < 1) {
            return 0;
        }
        
        int noOfSquares = (int)Math.sqrt(n) + 1;
        int[] squareNumbers = new int[noOfSquares];
        
        for(int i = 1; i < noOfSquares; i++) {
            squareNumbers[i] = i*i;
        }
        
        int[] dp = new int[n+1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        
        for(int i = 1; i <= n; i++) {
            for(int s = 1; s < noOfSquares; s++) {
                int squareNumber = squareNumbers[s];
                if(i < squareNumber) {
                    break;
                }
                dp[i] = Math.min(dp[i], dp[i-squareNumber]+1);
            }
        }
        
        return dp[n];
    }
}

Follow up

Last updated

Was this helpful?