I have an algorithm that calculates the maximum value of an expression that is made from numbers and * or + by adding parentheses. It has 3 nested loops, so the time complexity should be N^3
static void printMinAndMaxValueOfExp(string exp)
{
List<int> num = new List<int>();
List<char> opr = new List<char>();
string tmp = "";
// store operator and numbers in different vectors
for (int i = 0; i < exp.Length; i++)
{
if (isOperator(exp[i]))
{
opr.Add(exp[i]);
num.Add(int.Parse(tmp));
tmp = "";
}
else
{
tmp += exp[i];
}
}
// storing last number in vector
num.Add(int.Parse(tmp));
int len = num.Count;
int[,] maxVal = new int[len, len];
// initializing minval and maxval 2D array
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
maxVal[i, j] = 0;
// initializing main diagonal by num values
if (i == j)
{
maxVal[i, j] = num[i];
}
}
}
// looping similar to matrix chain multiplication
// and updating 2D array
for (int L = 2; L <= len; L++)
{
for (int i = 0; i < len - L + 1; i++)
{
int j = i + L - 1;
for (int k = i; k < j; k++)
{
int maxTmp = 0;
// if current operator is '+', updating
// tmp variable by addition
if (opr[k] == '+')
{
maxTmp = maxVal[i, k] + maxVal[k + 1, j];
}
// if current operator is '*', updating
// tmp variable by multiplication
else if (opr[k] == '*')
{
maxTmp = maxVal[i, k] * maxVal[k + 1, j];
}
// updating array values by tmp
// variables
if (maxTmp > maxVal[i, j])
maxVal[i, j] = maxTmp;
}
}
}
// last element of first row will store the result
Console.Write("Maximum value : {0} " , maxVal[0, len - 1]);
}
But by timing the function using c# stopwatch
static public void Main()
{
string expression = "1+1+1+1+1";
Stopwatch Time = new Stopwatch();
Time.Start();
printMinAndMaxValueOfExp(expression);
Time.Stop();
Console.WriteLine(Time.ElapsedMilliseconds);
}
I get close to linear results. So am I wrong and the function is not of the complexity N^3, or am I timing it wrong?