import java.util.*;
/**
* 天猫超市购物:天猫超市购物,具有多种购物优惠活动,如:满99减50,满188减100,满288减150等,假设每种商品只能买一 * 次,小明现在支付宝有M元,请问小明如果购物能够使得购物的总价最大?
* 输入格式:第一行代表优惠活动,第二行代表商品价格,第三行代表支付宝余额M元
* 99-50,188-100,288-150
* 300,200,150,100,50,40,30,20,10,8,6,4,3,2,1
* 70
* @author NJUPT-MXW
*
*/
public class main1 {
static int Goods_Compute(String activityStr, String itemStr,
String amountStr) {
int result =0 ;
if (activityStr != null && itemStr != null && amountStr != null) {
String[] item_Str = itemStr.split(",");
int[] item_prices = new int[item_Str.length];
for (int i = 0; i < item_prices.length; i++) {
item_prices[i]=Integer.valueOf(item_Str[i].trim());
}
Arrays.sort(item_prices); //对输入的商品价格排序;
int amountMoney = Integer.valueOf(amountStr);
int act_num = activityStr.split(",").length;
String[][] activitys = new String[act_num][2];
for (int i = 0; i < activitys.length; i++) {
activitys[i][0] = activityStr.split(",")[i].split("-")[0]; // 99 188 288
activitys[i][1] = activityStr.split(",")[i].split("-")[1]; // 50 100 150
}
for (int i = 0; i < act_num; i++) {
int tmp = getBuySum(activitys[i][0] ,activitys[i][1],amountMoney,item_prices);
if(tmp > result)
result = tmp;
}
if(result == 0){
for (int i = item_prices.length - 1; i >= 0 ; i--) {
if((result + item_prices[i]) > amountMoney)
continue;
result += item_prices[i];
}
}
}
return result;
}
private static int getBuySum(String activity_price, String discount_price,
int amountMoney, int[] item_prices) {
int act_price = Integer.valueOf(activity_price);
int dis_price = Integer.valueOf(discount_price);
if((act_price - dis_price) > amountMoney )
return -1;
int buy_sum=0;
for (int i = item_prices.length - 1; i >= 0 ; i--) {
if((buy_sum + item_prices[i]) > (amountMoney+dis_price))
continue;
buy_sum += item_prices[i];
}
return buy_sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int res;
String _activityStr;
try {
_activityStr = in.nextLine();
} catch (Exception e) {
_activityStr = null;
}
String _itemStr;
try {
_itemStr = in.nextLine();
} catch (Exception e) {
_itemStr = null;
}
String _amountStr;
try {
_amountStr = in.nextLine();
} catch (Exception e) {
_amountStr = null;
}
res = Goods_Compute(_activityStr, _itemStr, _amountStr);
System.out.println(String.valueOf(res));
}
}
阿里笔试:天猫超市购物,具有多种购物优惠活动,如:满99减50,满188减100,满288减150等,假设每种商品只能买一次,小明现在支付宝有M元,请问小明如果购物能够使得购物的总价最大?
最新推荐文章于 2023-01-15 10:18:09 发布