最大子数组问题(一) 暴力求解

xiaoxiao2021-02-28  41

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)+"天出售"); }
转载请注明原文地址: https://www.6miu.com/read-2626031.html

最新回复(0)