分治最大子數組
阿新 • • 發佈:2018-06-13
ros ID class ret size only 數組下標 sum 分治
1 struct A 2 { 3 int maxright; // 記錄右邊最大子數組的下標 4 int maxleft; // 記錄左邊最大子數組的下標 5 int sum; // 記錄數組下標maxleft--maxright的元素和 6 }; 7 8 void Solution::maxSubarray(const vector<int>& vec) 9 { 10 int left = 0; 11 int right = vec.size() - 1;12 A result = findMaxSubarr(vec, left, right); 13 cout << "left_index:" << result.maxleft << ", "; 14 cout << "right_index:" << result.maxright <<", " ; 15 cout << "sum = " << result.sum << endl; 16 } 17 18 Solution::A Solution::findMaxSubarr(constvector<int>& vec, 19 int left, int right) 20 { 21 if(left == right) 22 { 23 // base case: only one element 24 A maxsubarr; 25 maxsubarr.maxleft = left; 26 maxsubarr.maxright = right; 27 maxsubarr.sum = vec[left]; 28 return maxsubarr;29 } else 30 { 31 int mid = (left + right) / 2; 32 A leftarr = findMaxSubarr(vec, left, mid); 33 A rightarr = findMaxSubarr(vec, mid+1, right); 34 A crossarr = findCrossSubarr(vec, left, mid, right); 35 if(leftarr.sum >= rightarr.sum && leftarr.sum >= crossarr.sum) 36 return leftarr; 37 else if(rightarr.sum >= leftarr.sum && 38 rightarr.sum >= crossarr.sum) 39 return rightarr; 40 else 41 return crossarr; 42 } 43 } 44 45 Solution::A Solution::findCrossSubarr(const vector<int>& vec, 46 int left, int mid, int right) 47 { 48 int leftSum = INT_MIN; 49 int sum = 0; 50 A maxsubarr; 51 maxsubarr.maxleft = 0; 52 for(int i = mid; i >= left; i--) 53 { 54 sum = sum + vec[i]; 55 if(sum > leftSum) 56 { 57 leftSum = sum; 58 maxsubarr.maxleft = i; 59 } 60 61 } 62 63 int rightsum = INT_MIN; 64 sum = 0; 65 for(int j = mid+1; j <= right; j++) 66 { 67 sum = sum + vec[j]; 68 if(sum > rightsum) 69 { 70 rightsum = sum; 71 maxsubarr.maxright = j; 72 } 73 } 74 maxsubarr.sum = leftSum + rightsum; 75 return maxsubarr; 76 }
分治最大子數組