simple c# solution


  • 0
    X
    public class Solution {
        public int Candy(int[] ratings) {
            
            if (ratings.Length == 0)
            {
                return 0;
            }
            
            Tuple<int, int>[] candyList = new Tuple<int, int>[ratings.Length];
            int sum = 0;
            int lastCandy = 0;
            int lastRating = Int32.MinValue;
            
            for (int i= 0; i<ratings.Length; i++)
            {
                if (ratings[i] > lastRating)
                {
                    lastCandy +=1;
                }
                else if (ratings[i] == lastRating)
                {
                    lastCandy = 1;
                }
                else  // rating < lastRating
                {
                    lastCandy = 1;
                }
                
                sum+= lastCandy;
                candyList[i] = new Tuple<int, int>(ratings[i], lastCandy);
                lastRating = ratings[i];
            }
            
            for (int j = ratings.Length-1; j>0; j--)
            {
                if (candyList[j].Item1 < candyList[j-1].Item1 && candyList[j].Item2 >= candyList[j-1].Item2)
                {
                    int temp = candyList[j-1].Item2;
                    candyList[j-1] = new Tuple<int, int>(candyList[j-1].Item1, candyList[j].Item2 +1);
                    sum += candyList[j-1].Item2 - temp;
                }
            }
            
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.