[Leetcode] 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.

 

Solution:

只需要找到最大增长即可。如图所示,就是找到最大的红线。

从后往前,用此后最大价格减去当前价格,就是在当前点卖出股票能获得的最高利润。
扫描的过程中更新最大利润和最高价格就行了。

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         int maxProfit = 0;
 4         if (prices.length == 0)
 5             return maxProfit;
 6         int highest=prices[prices.length-1];
 7         for (int i = prices.length - 1; i >= 0; --i) {
 8             highest=Math.max(highest, prices[i]);
 9             maxProfit=Math.max(maxProfit, highest-prices[i]);
10         }
11         return maxProfit;
12     }
13 }

 

posted @ 2014-10-16 06:30  Phoebe815  阅读(128)  评论(0编辑  收藏  举报