Microsoft Interview Question
Software Engineer / DevelopersIterate over each element A - then iterate A+1 to N for O(n^2), then ping a hash table for the difference in O(1) in a typical case... Not really O(N^2), since a hashtable is O(N) but it's pretty safe to assume O(1) is reasonable for hashtable lookups.
Would you consider an algorithm that iterates over an array and pings a hashtable to be O(N^2)? I wouldn't, it would be misleading IMO.
This is an instance of knapsack problem. So we can use dynamic programming. The 'total' given can be thought of as the total value. The individual numbers represent individual values. Thee group size can be thought of as the weight constraint. Each number adds a weight equals 1. Solve the knapsack now.
//Use Recursion to solve it...runtime depends on array size and group size
//Brute force solution, generates nCg combinations
//where n - no. of elements & g - groupsize
//
- Anonymous June 16, 2009