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

版权声明:本文为博主原创文章,欢迎大家转载,但是要注明我的文章地址。 https://blog.csdn.net/program_developer/article/details/83245488

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

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<prices.length; i++) {
			if(prices[i] < minNum) {
				minNum = prices[i];
				index = i;
			}
			int temp = prices[i] - minNum;
			if(temp > 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<prices.length-1;i++)
    {
        local = Math.max(local+prices[i+1]-prices[i],0);
        global = Math.max(local, global);
    }
    return global;
}

Reference:

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

猜你喜欢

转载自blog.csdn.net/program_developer/article/details/83245488