TopCoder新算法记录:
今天做的TopCoder题如下:
Problem Statement | |||||||||||||
This task is about the scoring in the first phase of the die-game Yahtzee, where five dice are used. The score is determined by the values on the upward die faces after a roll. The player gets to choose a value, and all dice that show the chosen value are considered active. The score is simply the sum of values on active dice. Say, for instance, that a player ends up with the die faces showing 2, 2, 3, 5 and 4. Choosing the value two makes the dice showing 2 active and yields a score of 2 + 2 = 4, while choosing 5 makes the one die showing 5 active, yielding a score of 5. Your method will take as input a int[] toss, where each element represents the upward face of a die, and return the maximum possible score with these values. | |||||||||||||
Definition | |||||||||||||
| |||||||||||||
Limits | |||||||||||||
| |||||||||||||
Constraints | |||||||||||||
- | toss will contain exactly 5 elements. | ||||||||||||
- | Each element of toss will be between 1 and 6, inclusive. |
public class YahtzeeScore {
int ret;
public int maxPoints(int[] toss){
for(int i=1;i<=6;i++){
int count = 0;
for(int m:toss){
if(m==i){
count +=m;
ret = Math.max(ret, count);
}
}
}
return ret;
}
}
将一个数组遍历后,去求和,然后把和与初始为0的数比较,并且把其中大的数复制给ret,然后如此反复找出最大数
以下是我用的方法:
int ret = 0;
public int maxPoints1(int[] toss){
Map<Integer,Integer> map =new HashMap<Integer,Integer>();
for(int i = 0;i<toss.length;i++){
if(!map.containsKey(toss[i])){
map.put(toss[i], 1);
}else{
map.put(toss[i], map.get(toss[i])+1);
}
int result = toss[i]*map.get(toss[i]);
ret = Math.max(ret, result);
}
return ret;
}
使用hashmap,先求出数组中元素的出现次数,然后用map的key*value,求出总和,最后用遍历比较的方法去比较求出最大的值
topcoder这道题让我学会了遍历比较的方法
int count = 0
public static void xxxx(){
for(){
result=......;
ret = Math.max(count, result);
}
}