贪心算法-135
1 int candy(int* ratings, int ratingsSize) { 2 int *candys = NULL; 3 int resulte = 0; 4 5 candys = (int *)malloc(sizeof(int)*ratingsSize); 6 if (NULL == candys) 7 { 8 return 0; 9 } 10 candys[0] = 1; 11 for (int i = 1; i < ratingsSize; i++) 12 { 13 if (ratings[i] > ratings[i-1]) 14 { 15 candys[i] = candys[i-1] + 1; 16 } 17 else 18 { 19 candys[i] = 1; 20 } 21 } 22 resulte += candys[ratingsSize - 1]; 23 for (int i = ratingsSize - 1; i > 0; i--) 24 { 25 if (ratings[i - 1] > ratings[i]) 26 { 27 candys[i - 1] = fmax(candys[i - 1], candys[i] + 1); 28 } 29 resulte += candys[i - 1]; 30 } 31 return resulte; 32 }
1 int candy(int* ratings, int ratingsSize) { 2 int pre = 1, inc = 1, dec = 0; 3 int result = 1; 4 5 for(int i = 1; i < ratingsSize; i++) 6 { 7 if (ratings[i] >= ratings[i-1]) 8 { 9 dec = 0; 10 pre = ratings[i] == ratings[i-1] ? 1 : pre + 1; 11 result += pre; 12 inc = pre; 13 } 14 else 15 { 16 dec++; 17 if (dec == inc) 18 dec += 1; 19 pre = 1; 20 result += dec; 21 } 22 } 23 return result; 24 }