Sort by

recency

|

671 Discussions

|

  • + 0 comments

    Java:

        public static long candies(int n, List<Integer> arr) {
            long[] candies = new long[n];
            Arrays.fill(candies, 1);
            // Left to right
            for (int i=1; i<n; i++) {
                if (arr.get(i)>arr.get(i-1)) {
                    candies[i] = candies[i-1]+1;
                }
            }
            // Right to left
            for (int i=n-2; i>=0; i--) {
                if (arr.get(i)>arr.get(i+1)) {
                    candies[i] = Math.max(candies[i], candies[i+1]+1);
                }
            }
            return Arrays.stream(candies).sum();
        }
    
  • + 0 comments

    C++ Solution

    long long candies(unsigned n, vector<unsigned> arr) {
        vector<unsigned> candies(arr.size(), 1);
        
        for(unsigned i = 1; i < n; i++)
            if(arr[i] > arr[i-1])
                candies[i] = candies[i-1] + 1;
        
        for(int i = n - 2; i >= 0 ; i--)
            if(arr[i] > arr[i + 1])
                candies[i] = max(candies[i + 1] + 1, candies[i]);
    
        return accumulate(candies.begin(), candies.end(), static_cast<long long>(0));   
    }
    
  • + 0 comments

    Python solution

    def candies(n, arr):
        # Write your code here
        total_candy = [1] * n
        for i in range(1, n):
            if arr[i] > arr[i - 1]:
                total_candy[i] = total_candy[i - 1] + 1
        for i in range(n - 2, -1, -1):
            if arr[i] > arr[i + 1]:
                total_candy[i] = max(total_candy[i], total_candy[i + 1] + 1)
        
        # The result is the sum of all total_candy
        return sum(total_candy)
                    
    
  • + 0 comments

    No additional array used

    def candies(n, arr): total = 1 peak_index=0 peak_value = 1 last_value = 1 i = 1 while iarr[j]: j +=1 i = j-1 j -=2 last_value = 1 total += last_value while j>=peak_index: if (arr[j]>arr[j+1]): last_value += 1 else: last_value=1 total += last_value j -= 1 total -= peak_value total -= last_value total += max(peak_value, last_value) last_value=1 i += 1

    return total
    
  • + 0 comments

    RIP problem description. Extremely vague.