`
zhang_xzhi_xjtu
  • 浏览: 540202 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode] BestTimetoBuyandSellStock

阅读更多
package leetcode;

/**
* <pre>
* 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.
* </pre>
*/
public class BestTimetoBuyandSellStock {
    //slow.
    public class Solution {
        public int maxProfit(int[] prices) {
            if (prices == null || prices.length == 0)
                return 0;
            int result = prices[prices.length - 1] - prices[0];
            for (int step = prices.length - 2; step > 0; step--) {
                for (int i = 0; i + step < prices.length; i++) {
                    result = Math.max(result, prices[i + step] - prices[i]);
                }
            }
            return result;
        }
    }

    public class Solution2 {
        public int maxProfit(int[] prices) {
            if (prices == null || prices.length == 0)
                return 0;
            int result = 0;
            int min = prices[0];
            for (int i = 1; i < prices.length; i++) {
                result = Math.max(result, prices[i] - min);
                min = Math.min(min, prices[i]);
            }
            return result;
        }
    }
}
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics