In: Computer Science
Do only in C# (Not in C++ or C )
Minimum number of operations to convert array M to array N by adding an integer into a subarray
Given two arrays M and N , the task is to find the minimum number of operations in which the array M can be converted into array N where each operation consists of adding an integer K into a subarray from L to R.
M= {3, 7, 1, 4, 1, 2}, N = {3, 7, 3, 6, 3, 2}
Output: 1
In the above given example only one operation is required to
convert from M to N: L = 3, R = 5 and K = 2
Array after the following operation:
Index 0: M[0] = 3, N[0] = 3
Index 1: M[1] = 7, N[1] = 7
Index 2: M[2] = 1 + 2 = 3, N[2] = 3
Index 3: M[3] = 4 + 2 = 6, N[3] = 6
Index 4: M[4] = 1 + 2 = 3, N[4] = 3
Index 5: M[5] = 2, N[5] = 2
M= {1, 1, 1, 1, 1},N = {1, 2, 1, 3, 1}
Output: 2
In the above given example only one operation is required to
convert from M to N –
Operation 1: Add 1 to L = 2 to R = 2
Operation 2: Add 2 to L = 4 to R = 4
CODE :-
OUTPUT :-
TEXT CODE :-
using System;
namespace NoOfOperation
{
class Program
{
static void
Main(string[] args)
{
// Test Array 1
int[] M = { 3, 7, 1, 4, 1, 2 };
int[] N = { 3, 7, 3, 6, 3, 2 };
// Test Array 2
int[] M1 = { 1, 1, 1, 1, 1 };
int[] N1 = { 1, 2, 1, 3, 1 };
// Other Variables and Array
int[] minIndex = { -1, -1, -1, -1, -1, -1 };
int min = 0, steps = 0;
bool equal = false, first = true;
// Test With Array 1
do {
for (int i = 0; i < M.Length; i++)
{
if (M[i] != N[i])
{
if (min == 0)
{
min = N[i] - M[i];
minIndex[i] = 1;
} else if ((N[i] - M[i]) < min)
{
min = N[i] - M[i];
minIndex[i] = 1;
}else
{
minIndex[i] = 1;
}
}
}
for (int i = 0; i < M.Length; i++)
{
if(minIndex[i] == 1)
{
M[i] += min;
minIndex[i] = -1;
}
}
if(min == 0)
{
equal = true;
}
if(first == false)
{
steps += 1;
}
min = 0;
first = false;
} while (equal == false);
// Output
Console.WriteLine("Test With Array 1- \nOutput: {0}\n", steps);
// Variable Reset
steps = 0;
equal = false;
first = true;
// Test With Array 2
do
{
for (int i = 0; i < M1.Length; i++)
{
if (M1[i] != N1[i])
{
if (min == 0)
{
min = N1[i] - M1[i];
minIndex[i] = 1;
}
else if ((N1[i] - M1[i]) < min)
{
min = N1[i] - M1[i];
minIndex[i] = 1;
}
else
{
minIndex[i] = 1;
}
}
}
for (int i = 0; i < M1.Length; i++)
{
if (minIndex[i] == 1)
{
M1[i] += min;
minIndex[i] = -1;
}
}
if (min == 0)
{
equal = true;
}
if (first == false)
{
steps += 1;
}
min = 0;
first = false;
} while (equal == false);
// Output
Console.WriteLine("\nTest With Array 2- \nOutput: {0}\n",
steps);
}
}
}