【LeetCode-面试-算法】股票的最大盈利值

这个题目遇到两次:联想面试手写代码+码隆科技在线笔试。

LeetCode原题:

题号:121. Best Time to Buy and Sell Stock

链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

题目描述:

给定一个整形数组,其中的第i个元素代表股票第i天的价格。在一开始,你手里有足够的钱,但没有股票。你仅有一次买股票和一次卖股票的机会(每次只能买/卖1股),或者不买不卖。输出你可能的最大盈利值。尽量降低程序的时间复杂度。

样例1:

[7, 1, 5, 3, 6, 4],在价格为1的时候买入,在价格为6的时候卖出,可以得到最大盈利值为5。(5 = 6 - 1)

样例2:

[7, 6, 5, 4, 3, 2],选择不买不卖,最大盈利值为0。

思路分析:

(1)思路1:

重点:题中给明数据是股票数据,所以买入的时间一定是先于卖出的时间。

我们在遍历数组第i个数arr[i]的时候,我们先找出这个数之前的最小数值minNum,并记录最小数值在数组中的位置index。并比较当前值arr[i]与最小值minNum的差值,记录最大的差值,就是股票的最大盈利数。

已经AC的代码:

public class stockMax {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] array = {7, 1, 5, 3, 6, 4};
		int[] array1 = {7,6,5,4,3,2};
		System.out.println(maxProfit(array));
		System.out.println(maxProfit(array1));
	}
	
    public static int maxProfit(int[] prices) {
        if(prices.length == 0)
			return 0;
		int minNum = prices[0];
		int index = 0;
		int earn = 0;
		for(int i=1; i earn)
				earn = temp;
		}
		return earn;
    }
}

(2)思路2:动态规划

思路:维护两个变量,一个是到目前为止最好的交易,另一个是在当天卖出的最佳交易(也就是局部最优)。其实,就是求一个数组中连续子数组差最大。

状态转移方程为:

 local = Math.max(local+prices[i+1]-prices[i],0);

已经AC的代码:

public int maxProfit(int[] prices) {
    if(prices==null || prices.length==0)
        return 0;
    int local = 0;
    int global = 0;
    for(int i=0;i

Python 实现:

(1)动态规划解法:

题目的实质是:求连续子数组中差值和最大的那个差值和。

【LeetCode-面试-算法】股票的最大盈利值_第1张图片

class Solution:

    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if prices == None or len(prices) == 0:
            return  0
        dp = [0 for _ in range(0, len(prices))]
        for i in range(1,len(prices)):
            diff_profit = prices[i] - prices[i-1]
            if diff_profit + dp[i-1] <= 0:
                dp[i] = 0
            else:
                dp[i] = diff_profit + dp[i-1]
        return  max(dp)

solution = Solution()
# test 1
#stock = [7, 1, 5, 3, 6, 4]
# test 2
# stock = [7, 6, 4, 3, 1]
# test 3
stock = []
print(solution.maxProfit(stock))

Reference:

【1】https://blog.csdn.net/linhuanmars/article/details/23162793

你可能感兴趣的:(算法,LeetCode)