321
社区成员




下面是一个一维数组的 “最大子数组的和” 的动态规划的解法
# 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)