Java easiest solution
Ugly numbers ii--->https://leetcode.com/problems/ugly-number-ii/discuss/1738926/Java-easiest-solution\nThe only difference is we here are using factors as given
Ugly numbers ii--->[https://leetcode.com/problems/ugly-number-ii/discuss/1738926/Java-easiest-solution](http://)\nThe only difference is we here are using factors as given in array.\n```\nclass Solution {\n    public int nthSuperUglyNumber(int n, int[] primes) {\n        int[]dp=new int[n];\n        dp[0]=1;\n        int[]index=new int[primes.length];\n        for(int i=1;i<n;i++){\n            int min=Integer.MAX_VALUE;\n            for(int j=0;j<primes.length;j++){\n                min=Math.min(min,primes[j]*dp[index[j]]);\n            }\n            dp[i]=min;\n            for(int j=0;j<primes.length;j++){\n                if(min==primes[j]*dp[index[j]])index[j]++;\n            }\n        }\n        return dp[n-1];\n    }\n}\n```\n\nAlso adding an optimized solution where we are storing next values of all factors so that we dont have to calculate them again and again\n```\nclass Solution {\n    public int nthSuperUglyNumber(int n, int[] primes) {\n        int[]dp=new int[n];\n        int[]index=new int[primes.length];\n        int[]val=new int[primes.length];\n        Arrays.fill(val,1);\n        int next=1;\n        for(int i=0;i<n;i++){\n            dp[i]=next;\n            next=Integer.MAX_VALUE;\n            for(int j=0;j<primes.length;j++){\n                if(dp[i]==val[j])val[j]=dp[index[j]++]*primes[j];\n                next=Math.min(next,val[j]);\n            }\n        }\n        return dp[n-1];\n    }\n}\n```\n
['Java']