So I solved Fractional Knapsack problem:
There are n items in a store. For i =1,2, . . . , n, item i has weight wi > 0 and worth vi > 0. Thief can carry a maximum weight of W pounds in a knapsack. In this version of a problem the items can be broken into smaller piece, so the thief may decide to carry only a fraction xi of object i, where 0 ≤ xi ≤ 1. Item i contributes xiwi to the total weight in the knapsack, and xivi to the value of the load. In Symbol, the fraction knapsack problem can be stated as follows. maximize nSi=1 xivi subject to constraint nSi=1 xiwi ≤ W It is clear that an optimal solution must fill the knapsack exactly, for otherwise we could add a fraction of one of the remaining objects and increase the value of the load. Thus in an optimal solution nSi=1 xiwi = W
import java.util.Scanner;
public class FractionalKnapsack{
static int[] value;
static int[] weight;
static float[] ratio;
static int knapSackWeight;
static void getMaximumBenefit() {
int currentWeight = 0;
float benefit = 0;
while(currentWeight < knapSackWeight) {
int item = getMaxRatioItem();
//No items left
if(item == -1) {
break;
}
for(int i=0;i<weight[item];i++) {
if(currentWeight+ratio[item]<=knapSackWeight) {
currentWeight++;
benefit = benefit + ratio[item];
}
}
//Removing the item from array
ratio[item] = 0;
}
System.out.println("Weight: " + currentWeight + " Benefit: " + benefit);
}
static int getMaxRatioItem() {
float maxRatio = 0;
int ratioIndex = -1;
//Getting max ratio
for(int i=0;i < ratio.length;i++) {
System.out.println(ratio[i]);
if(ratio[i] > maxRatio) {
maxRatio = ratio[i];
ratioIndex = i;
}
}
return ratioIndex;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
value = new int[n];
weight = new int[n];
ratio = new float[n];
for (int i = 0; i < n; i++) {
weight[i] = in.nextInt();
value[i] = in.nextInt();
ratio[i] = (float)value[i] / weight[i];
}
knapSackWeight = in.nextInt();
getMaximumBenefit();
}
}
Is there any better solution? The running time will be n^2?