static void knapsack(int n, int\[\] weight, int\[\] profit, int capacity){
int x\[\] = new int\[n\] ;
int tp=0; //total profit
int i;
for( i = 0; i < n; i++){
x[i] = 0;
}
for( i = 0; i < n; i++){
if(weight[i] > capacity){
x[i] = 0;
}
else{
x[i] = 1;
tp = tp + profit[i];
capacity = capacity - weight[i];
}
}
tp = tp + (x[i] * profit[i]);
System.out.print("The vectors:");
for(i = 0; i < n; i++){
System.out.print("[" + x[i] + "]");
}
System.out.println("The maximum profit is:" + tp);
}
// Driver code
public static void main(String args[])
{
int profit[] = new int[] { 4, 2, 1, 10, 2 };
int weight[] = new int[] { 11, 2, 1, 4, 1 };
int W = 15;
int n = profit.length;
knapsack(n , weight, profit, W);
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 line 21 awhere it says tp = tp + (x[i] * profit[i]); how could i solve this