• + 1 comment

    I tried using Greedy approach and it passes all the tests (java)

    public static List<Integer> kFactorization(int n, List<Integer> nums) {
    		//List for storing the divisors of the numbers
    		List<Integer> ansNums = new ArrayList<>();
    		//Sort the nums in reverse order for minimum no of steps for reaching the number n
    		Collections.sort(nums, Collections.reverseOrder());
    		//initialize the flag to true
    		boolean isDiv = true;
    		//keep looping until we reached num from n to 1 and in each iteration number was divided.
    		while (isDiv && n >= 1) {
    			isDiv = false;	//set the flag to false to check if there was a divisor
    			for (int num : nums) {
    				if (n % num == 0) {	//if divisor found
    					ansNums.add(num);
    					n = n / num;
    					isDiv = true;	//set the flag true
    				}
    			}
    		}
    		Collections.sort(ansNums);	//sort the list bcz we added it in reverse order
    		List<Integer> ans = new ArrayList<>();
    		if (ansNums.isEmpty() || n != 1) {	//if we didn't reach the number, return -1
    			ans.add(-1);
    			return ans;
    		} else {
    			ans.add(1);	//else add initial 1 
    			//Multiply the number with divisors and add to the final list
    			for (int num : ansNums) {
    				ans.add(ans.get(ans.size() - 1) * num);
    			}
    			return ans;
    		}
    	}