关闭

【Leetcode】Best Time to Buy and Sell Stock

2676人阅读 评论(0) 收藏 举报
分类:

题目链接: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;  
}  


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:545405次
    • 积分:8453
    • 等级:
    • 排名:第2645名
    • 原创:305篇
    • 转载:6篇
    • 译文:0篇
    • 评论:35条
    博客专栏
    文章分类
    最新评论