Microsoft | L62 | On Site | Determine time complexity of this algorithm
Anonymous User
493

Let c be the size of cuts
Let n be the input value n which decides on the size of the total stick
What is the time complexity of this algorithm.

public class Solution { // C#
    public int MinCost(int n, int[] cuts) {
        int[,] dp = new int[n+1, n+1];
        for (var i = 0; i < n + 1; i++){
            for (var j = 0; j < n + 1; j++){
                dp[i, j] = Int32.MinValue;
            }
        }
        Func<int, int, int> dfs = null;
        dfs = (int lo, int hi) => {
            if (dp[lo, hi] != Int32.MinValue) return dp[lo, hi];
            var filteredCuts = cuts.Where(cut => lo < cut && cut < hi).ToArray();
            if (filteredCuts.Length == 0) return 0;
            int ans = Int32.MaxValue;
            foreach(var mid in filteredCuts){
                ans = Math.Min(ans, dfs(lo, mid) + dfs(mid, hi));
            }
            dp[lo, hi] = ans + hi - lo;
            return dp[lo, hi];
        };
        return dfs(0, n);
    }
} 

This seems to have been taken from https://leetcode.com/problems/minimum-cost-to-cut-a-stick/ but during the OA test I was not given the prompt.

Comments (0)