Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
850 B
2
Indexable
Never
class Solution {
public:
    int candy(vector<int>& rat) {
        int n=rat.size();
        vector<int>can(n,1);
        for(int i=1;i<n;i++){
            if(rat[i] > rat[i-1]) can[i]=can[i-1]+1;
        }
        for(int i=n-2;i>=0;i--){
            if(rat[i]>rat[i+1] && can[i]<=can[i+1]) can[i]=can[i+1]+1;
        }
    
        int s=0;
        for(auto i:can) s+=i;
        return s;
    }
};

PYTHON
class Solution:
    def candy(self, rat: List[int]) -> int:
        n=len(rat)
        can=[1]*n

        for i in range(1,n):
            if(rat[i]>rat[i-1]):
                can[i]=can[i-1]+1
        for i in range(n-2,-1,-1): #(start,stop,step) includes start buy not stop
            if(rat[i]>rat[i+1] and can[i]<=can[i+1]):
                can[i]=can[i+1]+1
        
        s=sum(can)
        return s
Leave a Comment