您的位置:首页 > 其它

【LEETCODE】53-Maximum Subarray

2015-12-10 16:04 155 查看
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.
click to show more practice.
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.

参考: http://www.cnblogs.com/zuoyuan/p/3781988.html


class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

tmpsum=0
maxsum=-100000

for i in range(0,len(nums)):
if tmpsum<0:
tmpsum=0
tmpsum+=nums[i]
maxsum=max(tmpsum,maxsum)
return maxsum


分治法:

下次有时间再仔细学习

参考:
http://www.algoqueue.com/algoqueue/default/view/10354688/find-maximum-sum-subarray-divide-and-conquer-
Divide the array into two parts.

Find maximum subarray sum for left half recursively.

Find maximum subarray sum for right half recursively.

Find maximum subarray sum for the subarray including the middle element. (Sum of last two steps)

Return the maximum of the last three results.

public static int FindMaxSumSubArray(int[] array, int low, int high){

/* No element in the array */
if (low > high)
return 0;
/* One element in the array */
if (low == high)
return max(0, array[low]);

/* Middle element of the array */
int middle = (low + high) / 2;

/* find maximum sum crossing to left */
leftMax = sum = 0;
for (i = middle; i ≥ low; i--) {
sum += array[i];
if (sum > leftMax)
leftMax = sum;
}

/* find maximum sum crossing to right */
rightMax = sum = 0;
for (i = middle+1; i ≤ high; i++) {
sum += array[i];
if (sum > rightMax)
rightMax = sum;
}

/* Return the maximum of leftMax, rightMax and their sum */
return Math.max(leftMax + rightMax,
Math.max(FindMaxSumSubArray(low, middle), FindMaxSumSubArray(middle+1, high)));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: