日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

逐步优化求解最大子序列和

發布時間:2023/12/13 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 逐步优化求解最大子序列和 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

求解最大子序列和

tag: 數據結構與算法


最大子序列和問題:

給定序列A1, A2,... AN, 求最大的子序列和。
例如 :
  對于序列4, -3, 5, -2, -1, 2, 6, -2, 最大序列和為11(4 -3 + 5 - 2 - 1 + 2 + 6)

算法一:

利用兩個循環,第一個循環把序列遍歷一遍,第二個循環則從Ai累加到AN,每加一次判斷一下是否大于之前的最大子序列和:

int maxSubsequenceSum1 (const int arr[], int n) {int maxSum = 0;int temp;for (int i = 0; i < n; i++) {temp = 0;for (int j = i; j < n; j++) {temp += arr[j];if (temp > maxSum)maxSum = temp;}}return maxSum; }

時間復雜度:O(n2

算法二:

首先把序列從中間一分為二, 則最大子序列和的存在有三種情況:

  • 全在左邊的子序列
  • 全在右邊的子序列
  • 處在中間
    對于第一和第二種情況,只需要遞歸調用求解函數,對于第三種情況則要分別求出從中間出發,向左邊和向右邊各自的最大子序列和。
  • int max(int a, int b, int c) {int max;if (a > b)max = a;else max = b;if (c > max)max = c;return max; }int maxSubsequenceSum2 (const int arr[], int begin, int end) {int maxLeftSum, maxRightSum, maxLeftCenterSum, maxRightCenterSum, center, temp;if (begin >= end) {if (arr[begin] > 0)return arr[begin];elsereturn 0;}center = (begin+end)/2;maxLeftSum = maxSubsequenceSum2(arr, begin, center);maxRightSum = maxSubsequenceSum2(arr, center+1, end);maxLeftCenterSum = 0;temp = 0;for (int i = center; i >= begin; i--) {temp += arr[i];if (temp > maxLeftCenterSum)maxLeftCenterSum = temp;}maxRightCenterSum = 0;temp = 0;for (int i = center+1; i <= end; i++) {temp += arr[i];if (temp > maxRightCenterSum)maxRightCenterSum = temp;}return max(maxLeftSum, maxRightSum, (maxLeftCenterSum+maxRightCenterSum)); }

    時間復雜度:O(nlogn)

    算法三:

    累加序列,若發現當前序列和大于之前最大序列和,則替換.若發現當前序列和小于0,則將當前序列和置換成0,相當于把前面的序列都舍棄掉.

    int maxSubsequenceSum3(int arr[], int n) {int tempSum = 0, maxSum = 0;for (int i = 0; i < n; i++) {tempSum += arr[i];if (tempSum < 0)tempSum = 0;if (tempSum > maxSum)maxSum = tempSum;}return maxSum; }

    時間復雜度:O(n)

    轉載于:https://www.cnblogs.com/bgmind/p/3959193.html

    總結

    以上是生活随笔為你收集整理的逐步优化求解最大子序列和的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。