class Program
{
static void Main(string[] args)
{
int[] priceArray = { 100, 113, 110, 85, 105, 102, 86, 63, 81, 101, 94, 106, 101, 79, 94, 90, 97 };
int[] priceFluctuationArray = new int[priceArray.Length - 1];//价格波动的数组
for (int i = 1; i < priceArray.Length; i++)
{
priceFluctuationArray[i - 1] = priceArray[i] - priceArray[i - 1];
}
//默认数组第一个元素为最大子数组
int total = priceFluctuationArray[0];
int totalTemp = 0;
int startIndex = 0;
int endIndex = 0;
//取得下标为i的所有子数组开头
for (int i = 0; i < priceFluctuationArray.Length; i++)
{
totalTemp = priceFluctuationArray[i];
//取得下标为j的子数组结尾
for(int j = i; j < priceFluctuationArray.Length; j++)
{
if (j>i)
{
totalTemp += priceFluctuationArray[j];
}
if (totalTemp > total)
{
total = totalTemp;
startIndex = i;
endIndex = j;
}
}
}
Console.WriteLine("第" + startIndex + "天购买,第" + (endIndex+1)+"天出售");
}
最大子数组问题(一) 暴力求解
最新推荐文章于 2021-08-27 09:50:30 发布