SRM285Div2,250

この記事は約3分で読めます。

We have some baskets containing apples, and we would like to perform the following procedure in a way that maximizes the number of remaining apples. First, we discard some (or none) of the baskets completely. Then, if the remaining baskets do not all contain the same number of apples, we remove excess apples from the baskets until they do.

You will be given a int[] apples where the i-th element of apples is the number of apples in the i-th basket. Return the number of apples remaining after the procedure described above is performed.

複数のりんごを含むいくつかのカゴがある。残っているりんごの数が最大になるように、次の手続きを行いたい。

  1. カゴのいくつか(or none)を完全に処分する。
  2. そしてもし残っているカゴのりんごの数が同じでなければ、同じになるまで、カゴから余分なりんごを取り除く。

例:apples={1,2,3}

なら、カゴを捨てないと、3個しか残らない(カゴの個3でカゴの中身は同じ数まで減らした結果1なので3*1)。

もし、1個しか入っていないカゴを捨てると、カゴは残り2つになるが、りんごは2個づつあるので、4個残るのでこっちのほうが多いので答えは4。

[java]
import java.util.Arrays;
public class BasketsWithApples {
public int removeExcess(int[] apples) {
Arrays.sort(apples);
System.out.println(Arrays.toString(apples));
int max=apples[0]*apples.length;
for (int i = 1; i < apples.length; i++) {
if (apples[i]*(apples.length-i)>max) {
max=apples[i]*(apples.length-i);
}
}
//System.out.println("max:"+max);
return max;
}
}

[/java]

if文を使わず、

[java]
if (apples[i]*(apples.length-i)>max) {
max=apples[i]*(apples.length-i);
}
[/java]

のところをMath.maxを使ったほうがかっこいいかな?

[java]
max=Math.max(apples[i]*(apples.length-i),max);
[/java]

コメント

タイトルとURLをコピーしました