简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
[−2,1,−3,4,−1,2,1,−5,4]
,the contiguous subarray
[4,−1,2,1]
has the largest sum = 6
.
More practice:
» Solve this problem
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
The first way to do it is to iterate through the whole array and use two variables, sum and max to dynamically record the max subarray value.
Cases can be concluded below,
1. All elements in array are negative, we just need to find the biggest one.
2. Have both negative and positive values.
(1) discard negative ones, while we need to find the maximum subarrays, so it possible that the maximum subarray includes both negative and positive values. In this case, we use a sum to record.
We use max to represent that maximum value of subarray. Assume that currently we have max>0, now we go ahead and scan. If A[i]<0, discard, go ahead. But if A[i]+A[i+1]+...+A[i+k]>0, then we need add Ai..k to subarray, and replace max = max + A[i]+...+A[i+k]. Based on the analysis above, we can have the algorithm given below.
The second way to do it is by divide and conquer.
Divide and conquer的那个解法好像是O(nlogn)的复杂度啊,不是O(n)的。
ReplyDeletegoogle这道题竟然把你这blog搜出来了。。。
ReplyDelete