阿里筆試:天貓超市購物,具有多種購物優惠活動,如:滿99減50,滿188減100,滿288減150等,假設每種商品只能買一次,小明現在支付寶有M元,請問小明如果購物能夠使得購物的總價最大?

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));


	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章