Minimum number of days in which no task is performed

• Difficulty Level : Medium
• Last Updated : 09 Dec, 2021

Given an array arr[] consisting of values (0, 1, 2, 3) of length N, representing the type of work that can be done on any ith day, such that the task is of either type A or type B. Each value in array is defined as:
0 – No tasks are available.
1 – Task of type B is available.
2 – Task of type A is available.

If the same type of task cannot be done for two consecutive days, the task is to minimize the number of days in which no task will be performed.

Examples:

Input: N = 4, arr = {0, 1, 3, 2}
Output : 2
Explanation : Following are the types of tasks done in each day.
On the 1st day there is no tasks so he does nothing and count becomes 1.
On the 2nd day, he performs task of type B.
On the 3rd day there are both tasks but as he had done task of type B on the previous day so he performs task A.
On the last day there is task A available but he had done the same task on the previous day so he does nothing and count becomes 2.
Therefore, 2 is the final answer.

Input: N = 8, arr[] = {0, 1, 3, 2, 0, 2, 3, 3}
Output: 3

Naive approach: This problem can be solved by using recursion. Follow the steps below to solve the given problem.

• Declare a variable say count = 0, to store the answer.
• If arr[i]=0, no task is there so do nothing and increase the count.
• If arr[i]=1, only task B is available, if the last day’s task was B then do nothing and increase the count else perform task B.
• If arr[i]=2, only task A is available, if the last day’s task was A then do nothing and increase the count else perform task A.
• If arr[i]=3, and the last day’s task was A then perform task B, if the last day’s task was B then perform task A, else perform the task which will minimize the number of days in which no task is performed.
• Use a variable last to keep track of the previous day’s task, which can take the following values :
• 0 – no task performed.
• 1 – the task of type A performed
• 2 – the task of type B performed

Below is the implementation of the above approach.

Javascript


Output
2

Efficient approach: To optimize the above approach Dynamic Programming can be used. Use memoization to store the previous state so that those previous states can be utilized to calculate further results.

Below is the implementation of the above approach:

Javascript


Output
2

Time Complexity: O(N), where N is the size of arr[].
Auxiliary Space: O(N), where N is the size of arr[].

My Personal Notes arrow_drop_up