Program/Algorithm_practice 1.2

本文介绍了一种使用在线/动态数组解决子列最大和问题的方法。通过遍历数组并跟踪当前和最大和,当遇到负数时重置当前和,确保找到连续子列的最大和。该算法的时间复杂度为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Program/Algorithm_practice 1.2

利用 online/dynamic array 解决子列最大和问题


  • key point
    scan the array by order
    nowsum saves the current answer
    maxsum always saving the max value
    and when nowsum is minus ,drop it ,
    cause a minus only reduces the following value

#include <stdio.h>
#include <stdlib.h>

int online (int list[],int N){  
//list ,length of list =N
	
	int nowsum=0,maxsum=0,i=0;
	while (i<=N-1)
	{
		nowsum+=list[i];
		if (nowsum<0) nowsum=0;//drop the minus
		else if (nowsum>maxsum) maxsum=nowsum;
		//maxsum always saving the max
		i++;
	}
	return maxsum ;
}

int main(){
	int N,i,result;
	printf("please input the length of list :\n");
	
	scanf("%d",&N);

	int *l; 
	//dynamic array
	
	l= (int*)malloc(sizeof(int)*N);

		if(l)
		{
		printf("input numbers divided by space:\n");
		for(i=0;i<N;i++) scanf("%d",l+i);
			printf("\n");
			printf("your list is :\n");
			  
		for(i=0;i<N;i++) printf("%d\t",l[i]);
			printf("\n");
		}
		else printf("error!");

        result =online(l,N);
		printf("\nthe result is %d",result);

		free(l);
		l=NULL;
}

  • result
please input the length of list :
8
input numbers divided by space:
4 -3 5 -2 -1 2 6 -2

your list is :
4       -3      5       -2      -1      2       6       -2

the result is 11
  • Time complexity
    O(n)O(n)O(n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值