candy.dart (1190B)
1 //Find how many candies each child gets based on their rating 2 //the time complexity of this code is O(n^2) where n is the number 3 //of children. 4 //Time: TLE 5 //Memory: TLE 6 class Solution { 7 int candy(List<int> ratings) { 8 int required_candies = ratings.length; 9 List<int> candies_given = []; 10 for(int i = 0 ; i < ratings.length ; ++i){ 11 candies_given.add(1); 12 } 13 bool done = false; 14 while(!done){ 15 done = true; 16 for(int i = 0 ; i < ratings.length; ++i){ 17 if(i != 0){ 18 if(candies_given[i] <= candies_given[i - 1] && ratings[i - 1] < ratings[i]){ 19 candies_given[i] = candies_given[i] + 1; 20 required_candies += 1; 21 done = false; 22 } 23 } 24 if(i != ratings.length - 1){ 25 if(candies_given[i + 1] >= candies_given[i] && ratings[i] > ratings[i + 1]){ 26 candies_given[i] = candies_given[i] + 1; 27 required_candies += 1; 28 done = false; 29 } 30 } 31 32 } 33 } 34 return required_candies; 35 } 36 }