贪心

返回首页

返回算法分类分析

第一题 Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1: Input: [7, 1, 5, 3, 6, 4] Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) Example 2: Input: [7, 6, 4, 3, 1] Output: 0

In this case, no transaction is done, i.e. max profit = 0.

解法

贪心在于所有的最佳利润都产生于自己和之前的最低值之间。

class Solution(object):

def __init__(self):
    self.minVal = 99999


def maxProfit(self, prices):
    """
    :type prices: List[int]
    :rtype: int
    """
    if not prices: return 0
    length = len(prices)
    profit = [0] * length
    for i in range(length):
        if self.minVal > prices[i]:
            self.minVal = prices[i]
        profit[i] = prices[i] - self.minVal
    return max(profit)

第二题 Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example: A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

解法

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

    if nums==None or nums==[] or nums[0]==0 and len(nums)>1:
        return False

    far=nums[0]

    for i in range(len(nums)):
        if far>=len(nums)-1:
            return True
        if i<=far:
            far=max(far,i+nums[i])


    return False    

第三题 Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example: Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

解法

class Solution(object):
def jump(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    ans = lastIdx = nextIdx = 0
    while nextIdx < len(nums) - 1:
        ans += 1
        lastIdx, nextIdx = nextIdx, max(i + nums[i] for i in xrange(lastIdx, nextIdx + 1))
    return ans    

第四题 Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解法

class Solution(object):
def maxProfit(self, prices):
    """
    :type prices: List[int]
    :rtype: int
    """
    total = 0
    for i in range(len(prices)-1):
        if prices[i] < prices[i+1]:
            total += prices[i+1] - prices[i]
    return total

第五题 Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

解法

from collections import deque

class Solution(object):
def lengthOfLongestSubstring(self, s):
    """
    :type s: str
    :rtype: int
    """
    chars = deque()
    longest = 0
    for c in s:
        if c in chars:
            length = len(chars)
            if length > longest: 
                longest = length
            while chars.popleft() != c:
                pass
        chars.append(c)

    return max(longest, len(chars))

第六题 Maximum Subarray

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.

解法

class Solution(object):
def maxSubArray(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    maxVal = -999999
    length = len(nums)
    if length == 0: return 0
    l, r, total = 0, 0, 0
    while r < length:
        total = total + nums[r]
        if maxVal < total:
            maxVal = total
        if total <= 0:
            r, l = r+1, r+1
            total = 0
        else:
            r = r+1
    return maxVal