I'm a newbie learning how to code, and I am trying to find the most efficient way to calculate the most profit from an array of stock prices. For a given array,I have a list of stock prices over n days. So for {1, 4, 5, 100}
, my maxProfit
would be 99
(100-1). The rule for maxProfit would be the greatest difference between two numbers in the Array where you cannot count backwards in the array.
I'm able to get the right solution, but it's not the most efficient. I'm striving for my solution to be \$O(n)\$. At the moment given that single loop and then the Max function, my solution is n^2 because there are two loops. Is there a way I can break it down to just one?
var stockPrices = new List<int>() { 30, 50, 3, 2, 1, 1, 10, 25, 2, 10 };
var maxProfit = 0;
for(int x = 0; x < stockPrices.ToArray().Length; x++)
{
int maxValue = stockPrices.Max();
int maxIndex = stockPrices.IndexOf(maxValue);
var allValuesToTheLeftOftheMax = stockPrices.GetRange(0, maxIndex);
//Find the min value
if (maxIndex == 0)
{
stockPrices.Remove(maxValue);
}
else
{
int minValue = allValuesToTheLeftOftheMax.Min();
//Get the max profit
if (maxProfit < maxValue - minValue)
{
maxProfit = maxValue - minValue;
}
stockPrices.Remove(maxValue);
}
Console.WriteLine("Max profit currently is {0}", maxProfit);
}
Console.WriteLine("Final max profit is {0}", maxProfit);
Console.ReadLine();