Google Interview Question
Software Engineer / DevelopersCountry: United States
we can assume all weights wi are smaller than w, otherwise just return min(vi) among wi's that exceed w.
Find the max among wi, say w_max , then apply knapsack on w+w_max -1 to find the minimum value. Scan through the list from w+1 to w+w_max-1 to find the min value here(besides 0s) . The min value here should be the answer.
TreeSet<Integer> possibleValues = …;
void fillAllPossiblevalues(List<Integer> values, List<Integer> weights, Integer weightLimit, int valueStored) {
possibleValues.add(valueStored);
for (int i =0 ; i<weights.size(); i++) {
if (weightLimit < weights.get(i)) continue;
fillAllPossibleValues(values,weights, weightLimit -weights.get(i), valueStored + values.get(i));
}
}
Now,
int minsoFar = 0;
for (Integer value : possibleValues) { //this will be in increasing order
if (value!=++minsoFar) {
return misoFar;
}
}
it should be
weights.get(i)
instead of
weights.get(0)
also, can u give a reason as to why Treeset is used for poosibleValues why not a normal HashLinkedSet
as linkedHashSet has a lesser insert complexity as compared to treeset, and since you need all values in sorted order, you can just traverse the linkedhashset in order(as in your problem you are inserting them in ascending order only )
Hi Astronaut,
You are right about the weights.get(i) mistake.
Why I have used Treeset is because it will give you the elements in sorted order while you are iterating.
Whereas linkedHashSet will give you the order in which elements were inserted!
Notice the comment "//this will be in increasing order"
here is my solution. I think the complexity is bad.
If someone has better implementation.
Please give out. I will very appreciate.
int KnapSack(int capacity, int v[], int w[], int index, int num) {
if(capacity<0 || index>=num)
return 10000;
if(capacity == 0)
return 0;
int a = v[index] + KnapSack(capacity-w[index], v, w, index, num);
int b = KnapSack(capacity, v, w, index+1, num);
return min(a, b);
}
int SmallestImpossible(int v[], int w[], int capacity, int num) {
int smallest = 10000, c = 0;
for(int i=0; i<num; i++) {
int tmp = KnapSack(capacity+w[i], v, w, 0, num);
if(tmp < smallest) {
smallest = tmp;
c = capacity+w[i];
}
//cout << capacity+w[i] << " " << tmp << endl;
}
return smallest;
}
1) Use knapsack problem to find the minimum value(instead of maximum) for Weight W. In the original algo instead of taking maximum value take minimum value for each Array[i] , 0<i<=W.
- Rajesh January 25, 20132) Now for each value of n, find the minimum index i in Array such that i+w[n]> W and note the value as Array[i]+v[n]. Update this value if the old value is greater than the new value