![]() |
VOOZH | about |
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:
However, the colors of apples cannot 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.
Examples:
Input: M = 10, K = 15, N = 0, S = 1, W = 0, E = 0
Output: 10
Explanation: It simply gets 10 apples from the 1st south treeInput: M = 10, K = 15, N = 3, S = 0, W = 1, E = 0
Output: -1
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 the east and west. For the north there is no red apple, so, neglect that. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
10
Time Complexity: O(1) // since no loop is used the algorithm takes constant space to execute
Auxiliary Space: O(1) // since no extra array is used the solution takes up constant space.