LeetCode 1715: Count Apples and Oranges

Database

Problem Description

Explanation:

To solve this problem, we need to count the number of apples and oranges that fall within a given range. We are given the positions of the trees, the distances the fruits fall from the trees, and the range of the house. We can iterate through the distances of the apples and oranges from their respective trees and check if the fruit falls within the range of the house. If it does, we increment the count for that fruit.

Algorithmic Idea:

  1. Iterate through the distances of apples from the apple tree and check if they fall within the range of the house.
  2. Iterate through the distances of oranges from the orange tree and check if they fall within the range of the house.
  3. Increment the count for each fruit that falls within the house range.

Time Complexity:

The time complexity of this solution is O(m + n), where m is the number of apples and n is the number of oranges.

Space Complexity:

The space complexity of this solution is O(1) as we are using a constant amount of extra space.

:

Solutions

class Solution {
    public int[] countApplesAndOranges(int s, int t, int a, int b, int[] apples, int[] oranges) {
        int appleCount = 0, orangeCount = 0;
        for (int apple : apples) {
            if (a + apple >= s && a + apple <= t) {
                appleCount++;
            }
        }
        for (int orange : oranges) {
            if (b + orange >= s && b + orange <= t) {
                orangeCount++;
            }
        }
        return new int[]{appleCount, orangeCount};
    }
}

Loading editor...