(每日一练32276)题目名称:一维数组的最大子数组和

文盲老顾
WEB应用领新星创作者
博客专家认证
2023-05-15 09:04:38

下面是一个一维数组的 “最大子数组的和” 的动态规划的解法

# include <iostream>
# include <stdio.h>
# include <string.h>
int MaxSum(int* arr, int size)
{
    int current = arr[0]; //current max sum
    int max = current;
    for (int i = 0; i < size; i++)
    {
        if (current < 0)
            current = 0;
        current += arr[i];
        if (current > max)
            max = current;
    }
    return max;
}
int main(void)
{
    char x[40], y[40];
    int a1[5] = { -1, 5, 6, -7, 3 };
    int a2[5] = { -5, -4, -8, -1, -10 };
    int a3[5] = { -1, 5, 6, -7, 10 };
    int max1, max2, max3;
    max1 = MaxSum(a1, 5);
    max2 = MaxSum(a2, 5); //这个应该返回 -1, 
    max3 = MaxSum(a3, 5);
}

如果我需要返回值返回这个最大子数组的开始和结束的下标,你要怎么修改这个程序?

第一行输入一个整数n,表示数组长度(n < 100000) 第二行输入数组元素

输出和最大的子数组的开始下标、结束下标

这次不是求最大和了,是要找出最大和的起始结束下标。老顾在从新捡起算法的时候,先碰到的就是这个题目:https://blog.csdn.net/superwfei/article/details/128983274?spm=1001.2014.3001.5502

嗯,累赘的办法,还是从新写个吧

n = int(input())
arr = list(map(int,input().split()))
mx = max(arr)
if mx <= 0:
    print(arr.index(mx),arr.index(mx))
else:
    s,e,c,l,mx = 0,0,0,0,0
    for i in range(n):
        c += arr[i]
        if c < 0:
            c = 0
            l = 0
        else:
            l += 1
            if c > mx:
                mx = c
                e = i
                s = i - l + 1
    print(s,e)
...全文
109 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

321

社区成员

发帖
与我相关
我的任务
社区描述
主要用于技术交流,包括但不限于 .net,mssql,js,css,python,算法,运维。也可以晒最新技术,美图,运动等。最后,如果有问题,可以提问,老顾能帮忙的会尽量帮忙哦。
前端sqlserverasp.net 技术论坛(原bbs) 北京·西城区
社区管理员
  • 文盲老顾
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧