暴力求最大子数组

最大子数组问题(暴力法)

暴力求解:遍历每一个子数组区间,比较大小,并记录最大收益的开始和结束的下标

代码实现

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);


posted @   xiaoliangliang  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示