zoukankan      html  css  js  c++  java
  • LeetCode

     

    Description

    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.

    Example 1:

    Input: [7, 1, 5, 3, 6, 4]
    Output: 5

    max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

    Example 2:

    Input: [7, 6, 4, 3, 1]
    Output: 0

    Input: [7, 6, 4, 3, 1]
    Output: 0

    In this case, no transaction is done, i.e. max profit = 0.In this case, no transaction is done, i.e. max profit = 0.

    Solution

    A了题目53. maximum subarray之后,这一题思路就比较清晰了,相信各位看官稍动脑筋应该也能想到,或者看代码进行分析。

    当然,特别要注意列表为空的情况(此时应返回0!)

    python

     1 class Solution(object):
     2     def maxProfit(self, prices):
     3         """
     4         :type prices: List[int]
     5         :rtype: int
     6         """
     7         if len(prices) == 0:
     8             return 0
     9 
    10         max_diff = 0
    11         cur_diff = 0
    12         buy_price = prices[0]
    13         for item in prices[1:]:
    14             if item < buy_price:
    15                 buy_price = item
    16                 cur_diff = 0
    17             else:
    18                 cur_diff = item - buy_price
    19                 max_diff = max(max_diff, cur_diff)
    20 
    21         return max_diff

    cpp

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         if (prices.size()==0)
     5             return 0;
     6 
     7         int buy_price = prices.at(0);
     8         int max_diff = 0;
     9         int cur_diff = 0;
    10         int temp = 0;
    11         for (size_t i=1; i<prices.size(); ++i)
    12         {
    13             temp = prices.at(i);
    14             if (temp < buy_price)
    15             {
    16                 buy_price = temp;
    17                 cur_diff = 0;
    18             }else
    19             {
    20                 cur_diff = temp - buy_price;
    21                 max_diff = (max_diff < cur_diff ? cur_diff : max_diff);
    22             }
    23         }
    24 
    25         return max_diff;
    26     }
    27 };
     
  • 相关阅读:
    poj2411 状压dp
    棋盘覆盖TYVJ1035(二分图最大匹配)
    poj3417
    无向图边双+缩点
    无向图点双+缩点
    bzoj1123(割点加路径统计)
    【BZOJ1178】会议中心(APIO2009)-贪心+倍增+set
    【BZOJ4650】优秀的拆分(NOI2016)-后缀数组+RMQ+差分
    【BZOJ4569】萌萌哒(SCOI2016)-并查集+倍增
    【BZOJ2208】连通数(JSOI2010)-SCC+DP+bitset
  • 原文地址:https://www.cnblogs.com/gxcdream/p/7507404.html
Copyright © 2011-2022 走看看