Recently I was taking an online quiz and one of the code challenge is to find the maximal product number. I have came up with the below code with an algorithm. It took around 40 mins to write this so I accept it’s not a perfect code, but if anyone can improve it please do and let me know 🙂
List<int> total = new List<int>(); public int MaxAlgo(int input, string lpn) { int sum = 1, inp = input, mod; if (input == 0) { int num = Convert.ToInt32(lpn); while (num != 0) { mod = num % 10; num /= 10; sum *= mod; } total.Add(sum); } for (int i = Math.Min(inp, input); i >= 1; i--) { MaxAlgo(input - i, lpn + "" + i); } return sum; } public int MaximalProduct(int input) { if (input <= 0) { return 0; } else { MaxAlgo(input, ""); var rtnval = 0; for (int i = rtnval; i < total.Count; i++) { rtnval = Math.Max(rtnval, total[i]); } return rtnval; } }
Test : call the function “MaximalProduct(8)” which should return 18.
Note: I converted a string to int32, so it may throw a ‘System.OverflowException’ if the number is > 11