最大字段和(动态规划)

给定由n个整数(包含负整数)组成的序列a1,a2,…,an,求该序列子段和的最大值。
当所有整数均为负值时定义其最大子段和为0。
所求的最优值为:
在这里插入图片描述

例如,当(a1,a2, ……a7,a8)=(1,-3, 7,8,-4,12, -10,6)时,
最大子段和为:

在这里插入图片描述

#include<iostream>
#define MAX_LEN 1001
using namespace std;
int a[MAX_LEN];
void getMaxSum(int* a,int n){
    int besti;
    int bestj;
    int max=0;
    int temp=0;
    int begin=0;
    for(int i=0;i<n;i++){
        if(temp>0){
            temp+=a[i];
        }else{
            temp=a[i];
            begin=i;
        }
        if(max<temp){
            max=temp;
            besti=begin;
            bestj=i;
        }
    }
    cout<<max<<" "<<besti<<" "<<bestj;
}

int main(){
    int maxSum;
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    getMaxSum(a,n);
}

发布了84 篇原创文章 · 获赞 5 · 访问量 3558

猜你喜欢

转载自blog.csdn.net/qq_44824148/article/details/105056969
今日推荐