算法导论 4.1 最大子数组问题
Posted IKnowYou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法导论 4.1 最大子数组问题相关的知识,希望对你有一定的参考价值。
8. 实现代码
1 #include <iostream> 2 using namespace std; 3 4 const long long NINF = -1 << 30; 5 const int N = 100; 6 struct ans { 7 long long sum; 8 int left; 9 int right; 10 }; 11 12 13 ans FIND_CROSS_MAX_SUBARRAY(int a[], int low,int mid, int high) { 14 long long left_sum = NINF; 15 long long sum = 0; 16 int max_left; 17 18 for (int i = mid; i >= low; i--) { 19 sum = sum + a[i]; 20 if (sum > left_sum) { 21 left_sum = sum; 22 max_left = i; 23 } 24 } 25 26 long long right_sum = NINF; 27 sum = 0; 28 int max_right; 29 30 for (int j = mid + 1; j <= high; j++) { 31 sum += a[j]; 32 if (sum > right_sum) { 33 right_sum = sum; 34 max_right = j; 35 } 36 } 37 38 ans res{ 39 right_sum + left_sum,max_left,max_right 40 }; 41 return res; 42 } 43 44 45 ans FIND_MAX_SUBARRAY(int a[], int low, int high) { 46 if (low == high) { 47 ans res{ a[low],low,high }; 48 return res; 49 } 50 51 int mid = (low + high) / 2; 52 ans res1 = FIND_MAX_SUBARRAY(a, low, mid); 53 ans res2 = FIND_MAX_SUBARRAY(a, mid + 1, high); 54 ans res3 = FIND_CROSS_MAX_SUBARRAY(a, low,mid, high); 55 56 if (res1.sum >= res2.sum&&res1.sum >= res3.sum) 57 return res1; 58 if (res2.sum >= res1.sum&&res2.sum >= res3.sum) 59 return res2; 60 if (res3.sum >= res1.sum&&res3.sum >= res2.sum) 61 return res3; 62 } 63 64 65 int main() { 66 int n; 67 int a[N]; 68 69 while (cin >> n) { 70 for (int i = 1; i <= n; i++) 71 cin >> a[i]; 72 ans res = FIND_MAX_SUBARRAY(a, 1, n); 73 cout << "sum= " << res.sum << " [" << res.left << " , " << res.right << "]" << endl; 74 } 75 return 0; 76 }
1 4. 1-3 2 ans BRUTE_FIND_MAXIMUM_SUBARRAY(int a[], int low, int high) { 3 int sum = NINF; 4 int left_i, right_j; 5 ans res; 6 7 for (int i = low; i <= high; i++) 8 for (int j = low; j <= high; j++) { 9 int tmp = 0; 10 for (int k = i; k <= j; k++) 11 tmp += a[k]; 12 if (sum < tmp) { 13 sum = tmp; 14 left_i = i; 15 right_j = j; 16 } 17 } 18 res.sum = sum; 19 res.right = right_j; 20 res.left = left_i; 21 return res; 22 }
实现代码 ans LINER_TIME_FIND_MAXIMUM_SUBARRAY(int a[], int n) { int sum = a[1], Start = 1, End = 1; int tsum = a[1], tstart = 1, tend = 1; for (int i = 2; i <= n; i++) { if (tsum < 0) { tstart = tend = i; tsum = a[i]; } else { tend = i; tsum += a[i]; } if (tsum > sum) { sum = tsum; Start = tstart; End = tend; } } ans res{ sum,Start,End }; return res; }
以上是关于算法导论 4.1 最大子数组问题的主要内容,如果未能解决你的问题,请参考以下文章
文心一言 VS 讯飞星火 VS chatgpt (18)-- 算法导论4.1 5题