码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode-Best Time to Buy and Sell Stock -java

时间:2017-06-10 16:54:15      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:_for   base   otto   大小   tracking   length   span   family   tom   

题目:

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 class Solution {
    public int maxProfit(int[] prices) {
        int lowest = 0;
        int maxProfit = 0;
        if(prices.length > 0){
            lowest = prices[0];
            for(int i = 0; i < prices.length; i++){
                if(lowest > prices[i]){
                    lowest = prices[i];
                }
                maxProfit = Math.max(maxProfit, prices[i] - lowest);
            }
        }
        return maxProfit;
    }
}



PS:
Math.max(val1, val2);用来比較val1和val2的大小

Leetcode-Best Time to Buy and Sell Stock -java

标签:_for   base   otto   大小   tracking   length   span   family   tom   

原文地址:http://www.cnblogs.com/cynchanpin/p/6978914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!