最大子序和問題

來源:互聯網
上載者:User

最大子序和問題:給定整數A1,A2,.....An(可能有負數),求A1 +A2+A3+......+An的最大值(規定:如果所有整數均為負數,則最大子序和為0)

例:

輸入-2, 11, -4, 13, -5, -2時,答案為20(從A2到A4)。

下面給出四種不同複雜度的演算法,進行比較分析

O(n3)的演算法(窮舉所有可能)

<span style="font-size:18px;">public static int maxSubsequenceSum(int[] nums) {int ThisSum = 0;int MaxSum = 0; for (int i = 0; i < nums.length; i++) {for (int j = i; j < nums.length; j++) {ThisSum = 0;for (int k = i; k < j; k++) { ThisSum += nums[k];}  if (ThisSum > MaxSum)  MaxSum = ThisSum;   }  } return MaxSum;   }}</span>

<span style="font-size:18px;">O(n2)的演算法(去掉一次for迴圈)</span><pre name="code" class="java"><span style="font-size:18px;">public static int maxSubsequenceSum(int[] nums) {int ThisSum = 0;        int MaxSum = 0;for (int i = 0; i < nums.length; i++) {ThisSum = 0; for (int j = i; j < nums.length; j++) {ThisSum += nums[j]; if (ThisSum > MaxSum)       MaxSum = ThisSum;  } }  return MaxSum;  }}</span>

O(nlogn)的演算法(利用分治的策略,代碼比較複雜)

<span style="font-size:18px;">public static int maxSubSum(int[] nums, int Left, int Right) {int MaxLeftSum, MaxRightSum;if (Left == Right){if (nums[0] > 0)return nums[0];elsereturn 0; } int Center = (Left + Right) / 2;        MaxLeftSum = maxSubSum(nums, Left, Center);MaxRightSum = maxSubSum(nums, Center + 1, Right);int MaxLeftBorderSum = 0, LeftBorderSum = 0; for (int i = Center; i >= Left; i--) { LeftBorderSum += nums[i];if (LeftBorderSum > MaxLeftBorderSum) MaxLeftBorderSum = LeftBorderSum; } int MaxRightBorderSum = 0, RightBorderSum = 0;for (int i = Center + 1; i < Right; i++) {RightBorderSum += nums[i]; if (RightBorderSum > MaxRightBorderSum) MaxRightBorderSum = RightBorderSum;} int max = MaxLeftSum;max = (max < MaxLeftSum ? MaxLeftSum : max);max = (max < (MaxLeftBorderSum + MaxRightBorderSum) ? (MaxLeftBorderSum + MaxRightBorderSum) : max);return max;}</span>

O(n)的演算法(最為巧妙地演算法)

<span style="font-size:18px;">public static int maxSum(int[] nums) {int thisSum = 0;int maxSum = 0;for (int i = 0; i <nums.length; i++){thisSum += nums[i];if (maxSum < thisSum){maxSum = thisSum;}if (thisSum < 0){thisSum = 0;}}return maxSum;}</span>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.