Easy to get maximum dynamic programming of the sub-segments and issues

  • [Problems] Description
    is given by a sequence of n integers a1, a2, ..., a ( n), and selecting the maximum value of the sequence field.
  • Analysis of
    the definition of the maximum field when all are negative integers and zero.
  • Definition:
    Here Insert Picture Description
    i.e. 0 or the maximum value of i to the sequence between the sequences of both of j.
  • For example: the sequence (-2,11, -4,13, -5, -2), and to find the maximum field:
    max. 11 = + (-. 4) = 20 is + 13 is
#include<iostream>
const int MAX_LEN =100;

using namespace std;

int getMaxSum(int* a,int n){
    int max=0;//假设最大值为0
    int temp=0;
    for(int i=0;i<n;i++){
        if(temp>0){
            temp+=a[i];//最大值临时变量只有大于零,才可能越加越大
        }else{
            temp=a[i];////最大值临时变量只有小于零,直接等于a[i],否则越加越小
        }
        if(max<temp){
            max=temp;//判断赋值
        }
    }
    return max;
}

int main(){
    int a[MAX_LEN];
    int maxSum;
    int n;
	cout<<"请输入序列的元素个数"<<endl;
    cin>>n;
	cout<<"请依次输入序列的元素"<<endl;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    maxSum=getMaxSum(a,n);
    cout<<maxSum<<endl;
} 
Published 50 original articles · won praise 8 · views 3060

Guess you like

Origin blog.csdn.net/jiahuan_/article/details/105226916