求一组数字里面最大的子数组的和
第一种暴力解决
但是发现很多重复计算的值可以省略的。
下面是优化
用分而治之的算法
对于跨越的数组
这里求解最大值
找左边最大的子数组
找右边最大的子数组
相加就是最大子数组
分
治与合
整体思路:就是从分到治到合的过程
using System;
namespace cchoop
{
class Program
{
public static void Main()
{
int[] price = new int[] { 100, 113, 110, 85, 105, 102, 86, 63, 81, 101, 94, 106, 101, 79, 94, 90, 97 };
int[] priceChange = new int[price.Length - 1];
for (int i = 1; i < price.Length; i++)
{
priceChange[i - 1] = price[i] - price[i - 1];
}
MaxProfit maxProfit = GetMaxProfit(priceChange, 0, priceChange.Length - 1);
Console.WriteLine("最大收益为:{0},第{1}天买入,第{2}天卖出", maxProfit.ProfitNum, maxProfit.StartIndex, maxProfit.EndIndex + 1);
}
public static MaxProfit GetMaxProfit(int[] priceChange, int low, int high)
{
if (low == high)
{
MaxProfit maxProfit;
maxProfit.StartIndex = low;
maxProfit.EndIndex = high;
maxProfit.ProfitNum = priceChange[low];
return maxProfit;
}
int mid = (low + high) / 2;
//startIndex、endIndex都在mid左边
MaxProfit maxProfitLeft = GetMaxProfit(priceChange, low, mid);
//startIndex、endIndex都在mid右边
MaxProfit maxProfitRight = GetMaxProfit(priceChange, mid + 1, high);
//startIndex在mid左边,endIndex在mid右边
int startIndex = mid;
int endIndex = mid;
int totalProfit = priceChange[mid];
int tempProfit = 0;
//左边
for (int i = mid; i >= 0; i--)
{
tempProfit += priceChange[i];
if (tempProfit > totalProfit)
{
totalProfit = tempProfit;
startIndex = i;
}
}
//右边
tempProfit = totalProfit;
for (int i = mid + 1; i < priceChange.Length; i++)
{
tempProfit += priceChange[i];
if (tempProfit > totalProfit)
{
totalProfit = tempProfit;
endIndex = i;
}
}
MaxProfit maxProfitMid;
maxProfitMid.StartIndex = startIndex;
maxProfitMid.EndIndex = endIndex;
maxProfitMid.ProfitNum = totalProfit;
//比较 三个maxProfit
MaxProfit tempMaxProfit = maxProfitLeft;
if (maxProfitMid.ProfitNum > tempMaxProfit.ProfitNum)
{
tempMaxProfit = maxProfitMid;
}
if (maxProfitRight.ProfitNum > tempMaxProfit.ProfitNum)
{
tempMaxProfit = maxProfitRight;
}
return tempMaxProfit;
}
}
struct MaxProfit
{
public int StartIndex;
public int EndIndex;
public int ProfitNum;
}
}