121. 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.

链接: http://leetcode.com/problems/best-time-to-buy-and-sell-stock/

一刷,存min和profit

class Solution(object):
    def maxProfit(self, prices):
        if not prices:
            return 0
        lowest = prices[0]
        profit = 0
        for idx in range(len(prices)):
            if prices[idx] < lowest:
                lowest = prices[idx]
            elif prices[idx] - lowest > profit:
                profit = prices[idx] - lowest
        return profit

2/18/2017, Java

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

4/16/2017

BB电面准备

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if (prices.length <= 0) return 0;
 4         int min = prices[0];
 5         int maxProfit = 0;
 6         
 7         for (int i = 1; i < prices.length; i++) {
 8             if (prices[i] < min) {
 9                 min = prices[i];
10             } else if (prices[i] > prices[i - 1] && prices[i] - min > maxProfit) {
11                 maxProfit = prices[i] - min;
12             }
13         }
14         return maxProfit;
15     }
16 }

 

posted @ 2016-06-24 10:13  panini  阅读(124)  评论(0编辑  收藏  举报