Why adding "static" makes such a huge difference?


  • 0
    M

    My original solution looks exactly like below except that I did not have the "static" keyword for the methods. The solution was accepted but the runtime was ugly, like > 800 ms. However, after adding the "static", the runtime went down to only 48 ms... could anybody explain why? Thanks.

    public class Solution {
        
        private static Map<Integer, Integer> map = new HashMap<>();
        
        public static int numSquares(int n) {
            if (map.containsKey(n))
            {
                return map.get(n);
            }
            
            if (n == 0)
            {
                return 0;   
            }
            
            int largestNum = (int)Math.floor(Math.sqrt(n));
            int ans = Integer.MAX_VALUE;
            for (int i = largestNum; i >= 1; i--)
            {
                ans = Math.min(ans, 1 + numSquares(n - i*i));
            }
            map.put(n, ans);
            return ans;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.