leetcode--Best Time to Buy and Sell Stock

来源:互联网 发布:在淘宝买手机是真品吗 编辑:程序博客网 时间:2024/05/16 05:51

题目大概意思是说,给一个整形数组,每个数表示股票的成交价,然后由你决定哪一天买进,哪一天卖出使得利益最大。注意一下,要先买进,同一天是可以买进卖出的,只是利益为零。
动态规划基本题,将大问题转换为一个个阶段的小问题。用buy指示在哪一天买,sell指示哪一天卖,每完成一次买卖,用profit存下获益值,每个阶段都会产生一个profit,并比较阶段内最适合的买进值,存为下一阶段的buy值。
逻辑比较简单,直接代码吧。

public class Solution {    public int maxProfit(int[] prices) {        if(prices.length==0)return 0;        int buy = prices[0];        int sell = 0;        int profit = 0;        for(int price:prices){            sell = price;            profit = Math.max(profit,sell-buy);            buy = Math.min(buy,price);        }        return profit;    }}
0 0
原创粉丝点击