最大連續子數組,動態規劃基礎

動規思想:ios

狀態轉移方程:temp[i] = (temp[i-1]>0?temp[i-1]:0)+a[i];數組

temp[i]表示以第i個數字結尾的子數組的最大和spa

分析題目可知:temp[i]由兩種狀況:code

1.當以第(i-1)個數字爲結尾的子數組中最大和temp(i-1)小於0時,若是把這個負數和第i個數相加,獲得的結果反而比第i個數自己還要小,因此這種狀況下(以第i個數字爲結尾的子數組)最大子數組和是第i個數自己。blog

2.若是以第(i-1)個數字爲結尾的子數組中最大和temp(i-1)大於0,與第i個數累加就獲得了以第i個數結尾的子數組中最大和。ci

因而咱們只需求出temp數組中最大的那個數即是最大子數組的和!get

(能夠看出這個狀態轉移方程並不是直接得出最大連續子數組和,而是得出以第i個數字結尾的子數組的最大和,由於要獲得最大連續子數組和,必須先獲得temp[i](i從0到n,就依次得出了子數組的各類可能),因而temp存的即是以i結尾的最大子數組和,挑出最大的即是整個數組的最大子數組和)io

上代碼:class

#include<iostream>
using namespace std;

int getMax(int *arr,int n,int start,int end){
    
    int max;
    int firstmax = arr[0];
    max = arr[0];
    for(int i=1;i<n;i++){
        if(firstmax<0){
            firstmax = arr[i];
            start = i;
        }else{
            firstmax += arr[i];
        }
        if(firstmax > max){
            max = firstmax;
            end = i;
        }
    }
    printf("數組下標爲%d到%d,和爲%d\n",start,end,max);
    return max;
    
}

int main(){
    int a[100];
    int n;
    int start=0,end=0;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    getMax(a,n,start,end);
    return 0;
}
相關文章
相關標籤/搜索