zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    队列安排
    杂物
    最大数
    牛券
    斐波那契数列 !有疑惑
    方格取数
    阶乘之和-魏国
    过河卒
    二分查找算法(转)
    求整数的二进制表示中1的个数 (转)
  • 原文地址:https://www.cnblogs.com/panini/p/5613259.html
Copyright © 2011-2022 走看看