暴力求最大子数组
最大子数组问题(暴力法)
暴力求解:遍历每一个子数组区间,比较大小,并记录最大收益的开始和结束的下标
代码实现
int[] priceArray = new int[] { 100, 120, 140, 50, 63, 89, 150, 162, 186, 20, 90, 48, 75,
97, 98 };
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 startIndex = 0;
int endIndex = 0;
for (int i = 0; i < priceFluctuationArray.Length; i++)
{
// 取得以i为子数组起点的所有子数组
for (int j = i; j < priceFluctuationArray.Length; j++)
{
// 由i j就确定了一个子数组
int totalTemp = 0; // 临时最大子数组的和
for (int index = i; index < j + 1; index++)
{
totalTemp += priceFluctuationArray[index];
}
if (totalTemp > total)
{
total = totalTemp;
startIndex = i;
endIndex = j;
}
}
}
Console.WriteLine(startIndex);
Console.WriteLine(endIndex+1);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下