您的位置:首页 > 理论基础 > 数据结构算法

c#数据结构之最大子数组问题(暴力解决法)

2017-02-28 16:19 218 查看
主要是利用3个循环把每一种可能性都遍历,然后得到最大子数组,缺点就是性能,时间消耗过大



“`

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace _002最大子数组问题之暴力求解法

{

class Program

{

static void Main(string[] args)

{

int[] priceArray = new int[] {100,113,110,85,105,102,86,63,81,101,94,106,101,79,94,90,97 };

int[] changeArray = new int[priceArray.Length - 1];//变化

for (int i = 0; i < priceArray.Length-1; i++)
{
changeArray[i] = priceArray[i + 1] - priceArray[i];//相对于前一天的变化值
}
int total = changeArray[0];//默认最大值
int startIndex = 0;//开始下标
int endIndex = 0;//结束下标
//用3个循环把每一个可能都遍历过去找到最大值
for (int i = 0; i < changeArray.Length; i++)
{
for (int j = i; j < changeArray.Length; j++)
{
int temp = 0;
for (int z = i; z < j+1; z++)
{
temp += changeArray[z];
}
if (temp > total)
{
total = temp;
startIndex = i;
endIndex = j;
}
}
}
Console.WriteLine(startIndex);
Console.WriteLine(endIndex);
Console.WriteLine(string.Format("购买日期是第{0}天,出售是第{1}天", startIndex,endIndex+1));
Console.ReadKey();
}
}


}



8f15
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: