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 }
  • 相关阅读:
    模板
    总结
    关于log方线段树
    [ICPC2014 WF]Sensor Network
    背包问题总结
    NOIP2020微信步数
    NOIP2020移球游戏
    CF643D Bearish Fanpages
    CF685C Optimal Point
    论恋爱对学习的促进作用
  • 原文地址:https://www.cnblogs.com/panini/p/5613259.html
Copyright © 2011-2022 走看看