Minimum number of Apples to be collected from trees to guarantee M red apples
There are different kinds of apple trees in the four directions (East, West, North, South), which may grow both red and green apples such that each tree grows exactly K apples, in the following manner:
- N – number of trees to the north do not have red apples.
- S – number of trees to the south do not have green apples.
- W – number of trees in the west have some red apples.
- E – number of trees in the east have some green apples.
However, the colors of apples can not be distinguished outside the house. So, the task is to find the minimum number of apples to be collected from the trees to guarantee M red apples. If it is not possible, print -1.
Input: M = 10, K = 15, N = 0, S = 1, W = 0, E = 0
Explanation: It simply gets 10 apples from the 1st south tree
Input: M = 10, K = 15, N = 3, S = 0, W = 1, E = 0
Explanation: There are no red apples in the South, North and East. But in the West there are atleast 1 red apple and total tree is 1, So, total no. of guaranteed red apple is 1 * 1 = 1 which is less than M.
Approach: Every apple in the south ensures that it is red. So first, take an apple from the south. In the East and West, there is at least 1 red apple in each tree. That’s why, for guaranteed it is considered that there is only 1 red apple on each tree in east and west. For the north there is no red apple, so, neglect that. Follow the steps below to solve the problem:
- If M is less than equal to S*K then print M.
- Else if M is less than equal to S*K+E+W then print S*K + (M-S*K) * K
- Else print -1.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)