シミュレーションするだけですが、indexをforループの外で宣言しているのを忘れて初期化忘れの不具合が出てしまいました。
using System; using System.Collections.Generic; using System.Text; public class CarrotBoxesEasy { public int theIndex(int[] carrots, int K) { int index = 0; for (int k = 0; k < K; k++) { index = 0; //これを忘れた for (int i = 1; i < carrots.Length; i++) if (carrots[index] < carrots[i]) index = i; carrots[index]--; } return index; } }
下記のようにforループの中でindexを返すようにしたほうがいいかもしれません。
using System; using System.Collections.Generic; using System.Text; public class CarrotBoxesEasy { public int theIndex(int[] carrots, int K) { for (int k = 0; k < K; k++) { int index = 0; for (int i = 1; i < carrots.Length; i++) if (carrots[index] < carrots[i]) index = i; carrots[index]--; if(k.Equals(K - 1)) return index; } throw new Exception("error"); } }