編程題] 打車
時間限制:1秒
空間限制:32768K
妞妞參加完Google Girl Hackathon之後,打車回到了牛家莊。
妞妞需要支付給出租車司機車費s元。妞妞身上一共有n個硬幣,第i個硬幣價值爲p[i]元。
妞妞想選擇儘量多的硬幣,使其總價值足以支付s元車費(即大於等於s)。
但是如果從妞妞支付的這些硬幣中移除一個或者多個硬幣,剩下的硬幣總價值還是足以支付車費的話,出租車司機是不會接受的。例如: 妞妞使用價值爲2,5,7的硬幣去支付s=11的車費,出租車司機是不會接受的,因爲價值爲2這個硬幣是可以移除的。
妞妞希望能選取最大數量的硬幣,使其總價值足以支付車費並且出租車司機能接受。
妞妞希望你能幫她計算最多可以支付多少個硬幣。
輸入描述:
輸入包括兩行, 第一行包括兩個正整數n和s(1 <= n <= 10, 1 <= s <= 1000), 表示妞妞的硬幣個數和需要支付的車費。 第二行包括n個正整數p[i] (1 <= p[i] <= 100),表示第i個硬幣的價值。 保證妞妞的n個硬幣價值總和是大於等於s。
輸出描述:
輸出一個整數, 表示妞妞最多可以支付的硬幣個數。
輸入例子1:
5 9 4 1 3 5 4
輸出例子1:
3
import java.io.*;
import java.lang.*;
import java.util.*;
/*
* 付車費,最多可以付出的硬幣個數
*/
public class Main{
public int[] Sort(int[] coinValue){ //sort coinValue since the minimum
Arrays.sort(coinValue);
return coinValue;
}
public void MostCoinNum(int[] coinValue,int s){
Arrays.sort(coinValue);
if(coinValue[0] >= s){ //only require one coin
System.out.println(1);
return;
}
int sum = 0;
for(int i = 0; i < coinValue.length; i++) { //need all coins
sum += coinValue[i];
}
if(sum == s ){
System.out.println(coinValue.length);
return;
}
int temp = 0;int i = 0;
while(temp < s) {
temp += coinValue[i];
i++;
}
for( int j = i-2; j >= 0; j--){
if( temp - s >= coinValue[j] ){
temp = temp - coinValue[j];
i--;
}
}
System.out.println(i);
return;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Main cf = new Main();
// System.out.print("please input the length");
/* int length = sc.nextInt();
System.out.print("please input the s");
int farenum = sc.nextInt();
int[] arr = new int[length];*/
// System.out.print("please input the length & s");
String st = sc.nextLine();
String[] starr = st.split(" ");
int length = Integer.parseInt(starr[0]);
int farenum = Integer.parseInt(starr[1]);
// System.out.print("please input the array");
String str = sc.nextLine();
String[] strarray = str.split(" ");
int[] arr = new int[length];
for(int i = 0; i < length; i++)
arr[i] = Integer.parseInt(strarray[i]);
cf.MostCoinNum(arr,farenum);
}
}