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.

    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
    
    In this case, no transaction is done, i.e. max profit = 0.

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         if(prices.size() <= 1){
     5             return 0;
     6         }
     7         
     8         int minP = prices[0];
     9         int profit = 0;
    10         
    11         for(int i = 1; i < prices.size(); i ++){
    12             minP = min(minP, prices[i]);
    13             profit = max(profit, prices[i]-minP);
    14         }
    15         return profit;
    16     }
    17 };
  • 相关阅读:
    第十二次作业
    Beta 冲刺(7/7)
    Beta 冲刺(6/7)
    Beta 冲刺(5/7)
    Beta 冲刺(4/7)
    Beta 冲刺(3/7)
    Beta 冲刺(2/7)
    第十次作业
    Beta 冲刺(1/7)
    福大软工 · 最终作业
  • 原文地址:https://www.cnblogs.com/sankexin/p/5871420.html
Copyright © 2011-2022 走看看