• + 0 comments

    i know there are solution L-R and R-L solution , however for practice putepose I try to solve it different . But why do my code give wrong answer

    def candies(n, arr):
        
        res = [1] * len(arr)
        i = 0
        
        while i < len(arr):
            
            if i == 0:
                if arr[i] < arr[i+1]:
                    i += 1
                    continue
            else:    
                if arr[i] > arr[i-1]:
                    res[i] = res[i-1] + 1
            
            if not i == n-1 and arr[i] >= arr[i+1]:
                longest_decrease = 1
                j = i
                
                while True:
                    if j == n-1 or arr[j] < arr[j+1] :
                        break
                    if arr[j] > arr[j+1]:
                        longest_decrease += 1
                    j += 1
            
                if not j == i:
                    
                    for ii in range(i, j+1):
                        res[ii] = max(res[ii], longest_decrease)
                        if ii == n - 1:
                            break
                        if arr[ii] == arr[ii+1]:
                            continue
                        longest_decrease -= 1
                        
                    i = j
                    
            i += 1
            
        return sum(res)