![]() |
VOOZH | about |
Given three arrays A[], B[] and C[] of size N each and two integers X and Y, the task is to, find the minimum cost to reach the end of the arrays with the following conditions:
Note: It's not possible to switch from 1st to 3rd array directly or vice versa.
Examples:
Input: X = 6, Y = 3
A[] = { 30, 10, 40, 2, 30, 30 }
B[] = { 10, -5, 10, 50, 7, 18 }
C[] = { 4, 20, 7, 23, 2, 10 }
Output: 75
Explanation: We select this elements at index (0 to N-1).
A[] = { 30, 10, 40, 2, 30, 30 }
B[] = { 10, -5, 10, 50, 7, 18 }
C[] = { 4, 20, 7, 23, 2, 10 }
From index 0 we have to select 30. So Total cost to traverse up to index 0 is 30.
Now At index 1, 3 options (10, -5, 20). So select -5 from 2nd array.
So extra X (X = 6) cost required to shift from 1st array to 2nd.
So Total cost to traverse up to index 1 is 30 + 6 - 5 = 31.
At index 2, select 10. So Total cost to traverse upto index 2 is 31+10= 41.
At index 3, select 2 from 1st array,
So extra X (X = 6) points required to shift from 2nd array to 1st.
So Total cost to traverse upto index 3 is 41+6+2 = 49 and so on.
So, total cost = 30 + (6+(-5)) + 10 + (6+2) + (6+7) + (3+10) = 75
6 and 3 are the extra costs required to change array.Input: X = -5, Y = 4
A[] = { 30, 10, -15, 10, 50, 7 }
B[] = { 4, 20, 7, 23, 2, 18 }
C[] = { 30, 10, 40, 2, 30, 10 }
Output: 34
Approach: The problem can be solved based on the Greedy Approach based on the following idea:
At each index try to include the element from the array that will include the minimum cost. And also keep in mind that we can go from A[] to B[], B[] to C[], B[] to A[] and C[] to B[] not from A[] to C[] or C[] to A[].
Follow the below steps to implement the idea:
Below is the implementation of the above approach.
75
Time Complexity: O(N)
Auxiliary space: O(N)