【Leetcode】Best Time to Buy and Sell Stock

题目链接:https://leetcode.com/problems/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.

思路:

当前元素的最大收益只跟前面最小元素有关。

算法:

public int maxProfit(int[] prices) {  
    int maxProfit = 0;  
    int minEle = Integer.MAX_VALUE;  
    for (int i = 0; i < prices.length; i++) {  
        maxProfit = Math.max(maxProfit, prices[i]-minEle);  
        minEle = Math.min(minEle, prices[i]);  
    }  
    return maxProfit;  
}  


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yeqiuzs/article/details/51558597
个人分类: leetcode
所属专栏: Leetcode题解java版
上一篇【Leetcode】Count and Say
下一篇【Leetcode】House Robber
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭