HDOJ 1231 最大和連續子序列 (LeetCode 53、劍指Offer42的拓展)

LeetCode 53、劍指Offer42   都是求   連續子序列的最大和,

https://leetcode.com/problems/maximum-subarray/

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int val = nums[0];
        int sum = val;
        int n = nums.size();
        for(int i=1;i<n;i++){
            if(val>0 && nums[i] + val > 0)
                val = nums[i]+val;
            else// if(nums[i]>=0 && val<=0)
                val = nums[i];
            sum = max(sum, val);
        }
        return sum;
    }
};

 

來自杭電OJ 1231這道題,不僅求最大和,還要給出子序列的首尾元素。

http://acm.hdu.edu.cn/showproblem.php?pid=1231

 

代碼:

#include<stdio.h>
#include<vector>

using namespace std;

int main()
{
    int n, i, tmp, start, end;
    while(1){
       scanf("%d", &n);
       if(n==0) 
          return 0;
       vector<int> a;
        end =0;
       for(i=0;i<n;i++){
          scanf("%d",&tmp);
          a.push_back(tmp);
       }
       int maxsum = a[0]; 
       int tmpsum = 0;

       for(i=1;i<n;i++){
           tmpsum+=a[i];
           if(tmpsum>maxsum) {
              maxsum = tmpsum;
              end = i;
           }
           if(tmpsum<0)
              tmpsum = 0;
       }
        int keep_max = maxsum;
        int keep_end = end;
        if(maxsum==0)
            start =end;
        else if(maxsum<0){
            start = 0;
            keep_end = n-1;
            keep_max = 0;
        }
        else{
           while(maxsum>0){
              maxsum-=a[end];
              end--;
           }
           start = end+1;
        }
        printf("%d %d %d\n",keep_max, a[start], a[keep_end]);  
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章