认为这可能行得通。
class ApartmentBuyer{
public static void main(String[] args){
int noOfApartments=10;
System.out.println("Program to find maximum profit from given set of buyers and apartments. \n total number of apartments="+noOfApartments);
int [] buyersNeed= {4, 1, 2, 3};
int [] price={8, 1, 10, 9};
print(buyersNeed);
print(price);
System.out.println("Maximum Profit="+findMaxProfit(noOfApartments,buyersNeed,price,price.length-1,0));
}
/**
*b={4} and p={1} and noOfApratment=4 , max profit=4
*b={4,1} and price{1,5} noOfApartment= 1, max profit=4
*Start from right most and go forward for recurence
**/
public static int findMaxProfit(int noOfApartments, int need[], int[] price, int pos, int profit){
if(need==null || price==null || need.length<1 || price.length<1 || price.length!=need.length|| pos<0 || pos>need.length) return profit;
if(noOfApartments<=0) return profit;
int currentProfit=0;
if(need[pos]<=noOfApartments) currentProfit= profit+need[pos]*price[pos];
System.out.println("No Of Apartments:"+noOfApartments+ "\t pos:"+pos+"\t profit:"+profit+ "\tneed[pos]"+need[pos]);noOfApartments
System.out.println("No Of Apartments:"+noOfApartments+ "\t pos:"+pos+"\t profit:"+profit+ "\tneed[pos]"+need[pos]);noOfApartments
return Math.max(findMaxProfit(noOfApartments-need[pos],need,price, pos-1,currentProfit), findMaxProfit(noOfApartments,need,price,pos-1,profit));
}
static void print(int... arr){
if(arr==null || arr.length<1) return;
System.out.print("[");
for(int i:arr)System.out.print(i+" ");
System.out.println("]");
}
}