Leetcode-918 Maximum Sum Circular Subarray(环形子数组的最大和)

 1 class Solution
 2 {
 3     public:
 4         int maxSumCycle(vector<int>&vec, int &left, int&right)
 5         {
 6             int maxsum = INT_MIN, curMaxSum = 0;
 7             int minsum = INT_MAX, curMinSum = 0;
 8             int sum = 0;
 9             int begin_max = 0, begin_min = 0;
10             int minLeft, minRight;
11             for(int i = 0; i < vec.size(); i++)
12             {
13                 sum += vec[i];
14                 if(curMaxSum >= 0)
15                 {
16                     curMaxSum += vec[i];
17                 }
18                 else
19                 {
20                     curMaxSum = vec[i];
21                     begin_max = i;
22                 }
23 
24                 if(maxsum < curMaxSum)
25                 {
26                     maxsum = curMaxSum;
27                     left = begin_max;
28                     right = i;
29                 }
30                 if(curMinSum <= 0)
31                 {
32                     curMinSum += vec[i];
33                 }
34                 else
35                 {
36                     curMinSum = vec[i];
37                     begin_min = i;
38                 }
39 
40                 if(minsum > curMinSum)
41                 {
42                     minsum = curMinSum;
43                     minLeft = begin_min;
44                     minRight = i;
45                 }
46             }
47             if(maxsum >= sum - minsum)
48                 return maxsum;
49             else
50             {
51                 left = minRight+1;
52                 right = minLeft-1;
53                 return sum - minsum;
54             }
55         }
56         int maxSubarraySumCircular(vector<int>& A)
57         {
58             int flag = 1;
59             int MIN = INT_MIN;
60             for(auto d:A)
61             {
62                 if(d>=0)
63                 {
64                     flag = 0;
65                     break;
66                 }    
67                 if(d>MIN)
68                     MIN = d;
69             }
70             if(flag)
71             {
72                 return MIN;
73             }
74             int a = 0,b = A.size()-1;
75             return maxSumCycle(A,a,b);
76         }
77 };

核心代码部分参考:https://www.cnblogs.com/TenosDoIt/p/3698246.html

posted @ 2018-10-09 19:23  Asurudo  阅读(444)  评论(0编辑  收藏  举报