Sunday, June 23, 2013

Maximum subarray@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历: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 [−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.
» Solve this problem

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. 

2 comments:

  1. Divide and conquer的那个解法好像是O(nlogn)的复杂度啊,不是O(n)的。

    ReplyDelete
  2. google这道题竟然把你这blog搜出来了。。。

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...