pat 1007

Maximum Subsequence Sum


思路:这个题就是最大连续子串和,并且要求输出子串在原串中的起始和结束位置

动态规划的经典问题

附代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Max_len 10010

int record[Max_len];
//-2 11 -4 13 -5 -2
typedef struct node{
	int value;
	int front;
}node;

node no[Max_len];

int main(){
	
	int n, i;
	int pos, max, num = 0;

	scanf("%d", &n);
	for(i = 0; i < n; i++){
		scanf("%d", &no[i].value);
		no[i].front = i;
		record[i] = no[i].value;
		if(no[i].value < 0){
			num ++;
		}
	}
	
	if(num == n){
		printf("%d %d %d\n", 0, no[0].value, no[n - 1].value);
		return 0;
	}

	for(i = 1; i < n; i++){
		if(no[i - 1].value > 0){
			no[i].value += no[i - 1].value;
			no[i].front = no[i - 1].front;
		}
	}
	
	max = no[0].value; pos = no[0].front;

	for(i = 1; i < n; i++){
		if(no[i].value > max){
			pos = i;
			max = no[i].value;
		}
	}

	printf("%d %d %d\n", max, record[no[pos].front], record[pos]);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值