---
# System prepended metadata

title: Leetcode 135
tags: [LeetCode]

---

# Leetcode 135
###### tags: `LeetCode`
**Solution 1 but Time Complexity is really not good...**

	  public static int candy(int[] ratings) {
	        int res2[] = new int [ratings.length];
	        for(int i = 0 ; i < ratings.length-1 ; i++) { 
	        	if(ratings[i] > ratings [i+1] && res2[i] <= res2[i+1]) {
	        		res2[i] += 1;
	        		for(int j = i ; j>0 ; j--) {
	        			if(ratings[j] < ratings[j-1] && res2[j] >= res2[j-1]){
	        				res2[j-1] = res2[j] +1;
	        			}else {
	        				break;
	        			}
	        		}
	        	}else if(ratings[i] < ratings [i+1] && res2[i] >= res2[i+1] ){
	        		res2[i+1] = res2[i] +1;
	        	}
	        }
	        int res = ratings.length ;
	        for(int i : res2) {
	        	res += i;
	        }
	        return res;
	  }

**another solution butw it's more faster**

    public int candy(int[] ratings) {
        if(ratings==null||ratings.length==0){
            return 0;
        }
        int[] temp=new int[ratings.length];
        int length=ratings.length;
        temp[0]=1;
        for(int i=1;i<length;i++){
            if(ratings[i]>ratings[i-1]){
                temp[i]=temp[i-1]+1;
            }
            else{
                temp[i]=1;
            }
        }	
        for(int i=length-2;i>=0;i--){
            if(ratings[i]>ratings[i+1]&&temp[i]<=temp[i+1]){
                temp[i]=temp[i+1]+1;
            }
        }
        int res=0;
        for(int num:temp){
            res+=num;
        }
        return res;
    } 
