1. 程式人生 > 實用技巧 >leetcode97:maximum -subarray

leetcode97:maximum -subarray

題目描述

請計算給出的陣列(至少含有一個數字)中具有最大和的子陣列(子陣列要求在原陣列中連續) 例如:給出的陣列為[−2,1,−3,4,−1,2,1,−5,4], 子陣列[−2,1,−3,4,−1,2,1,−5,4],具有最大的和:6. 拓展: 如果你已經提出了O(n)的解決方法,請嘗試使用分治演算法來解決這道題。這道題分治的解法更巧妙一些。

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array[−2,1,−3,4,−1,2,1,−5,4],

the contiguous subarray[4,−1,2,1]has the largest sum =6.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

示例1

輸入

複製
[1]

輸出

複製
1
示例2

輸入

複製
[-2,1,-3,4,-1,2,1,-5,4]

輸出

複製
6
class Solution {
public:
/**
*
* @param A int整型一維陣列
* @param n int A陣列長度
* @return int整型
*/
int maxSubArray(int* A, int n) {
// write code here
int sum=A[0],maxSum=A[0];
for (int i=1;i<n;i++){
if (sum<0)
sum=0;
sum+=A[i];
maxSum=max(maxSum,sum);
}
return maxSum;
}
};