标签:style blog color os io for 问题 ar
这个问题是算法导论的一个示例,为了讲解分治。
1 //算法导论中的分治策略版本 2 3 4 #include<iostream> 5 using namespace std; 6 int maxCrossSum(int a[], int begin, int mid, int end) 7 { 8 int sumLeft = a[mid]; 9 int sumNow=0; 10 for (int i = mid; i >= begin; --i) 11 { 12 sumNow += a[i]; 13 if (sumNow > sumLeft) 14 sumLeft = sumNow; 15 } 16 int sumRight = a[mid + 1]; 17 sumNow = 0; 18 for (int i = mid + 1; i <= end; ++i) 19 { 20 sumNow += a[i]; 21 if (sumNow > sumRight) 22 sumRight = sumNow; 23 } 24 return sumLeft + sumRight; 25 } 26 int maxSubArray(int a[], int begin, int end) 27 { 28 if (begin == end) 29 return a[begin]; 30 else 31 { 32 int mid = (begin + end) / 2; 33 int leftSum = maxSubArray(a, begin, mid); 34 int rightSum = maxSubArray(a, mid + 1, end); 35 int crossSum = maxCrossSum(a, begin, mid, end); 36 int sum; 37 if (leftSum > rightSum) 38 sum = leftSum; 39 else sum = rightSum; 40 if (sum < crossSum) 41 sum = crossSum; 42 return sum; 43 } 44 } 45 int main() 46 { 47 const int SIZE = 13; 48 int a[SIZE] = { -3, -15, 20, -3, -16, -23, 18, 20, -9, 12, -5, -22, 15 }; 49 int maxsubarray = maxSubArray(a, 0, 12); 50 cout << maxsubarray << endl; 51 system("pause");
这里提供一个更加简便的方法:
1 更加高效的版本,无须递归,O(n)的时间复杂度 2 #include<iostream> 8 using namespace std; 9 int maxSubArray(int a[], int begin, int end) 10 { 11 int sum = 0; 12 int i = 0; 13 int maxSum = 0; 14 for (int i = begin; i <= end; ++i) 15 { 16 sum += a[i]; 17 if (sum > maxSum) 18 maxSum = sum; 19 //cout << maxSum << endl; 20 if (sum < 0) 21 sum = 0; 22 } 23 24 return maxSum; 25 } 26 int main() 27 { 28 const int SIZE = 13; 29 int a[SIZE] = { -3, -15, 20, -3, -16, -23, 18, 20, -9, 12, -5, -22, 15 }; 30 int maxsubarray = maxSubArray(a, 0, 12); 31 cout << maxsubarray << endl; 32 system("pause"); 33 }
此处不得不说,后面的方法兼具大气魄,有远见等特点,方能如此简单便捷!
标签:style blog color os io for 问题 ar
原文地址:http://www.cnblogs.com/gaoduan/p/3893528.html