zoukankan      html  css  js  c++  java
  • [leetcode] 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.

    给定一个数组,第i个元素代表股票第i天的价钱,只允许作一次买卖操作,求最大的利润。

    从头到尾遍历一遍数组,不断的记录到当前为止的最低股价,并尝试计算以之前的最低股价买入,以当前的价格卖出,不断更新最大利润。时间复杂度o(n)。

    代码如下:

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4         if (prices.size() == 0) return 0;
     5         int buy=prices[0];
     6         int profit = 0;
     7         for (int i = 0; i<prices.size(); i++)
     8         {
     9             if(prices[i] >= buy)
    10             {
    11                 profit = max (prices[i] - buy ,profit);
    12             }
    13             else
    14             {
    15                 buy = prices[i];
    16             }
    17         }
    18         return profit;
    19     }
    20 };
  • 相关阅读:
    02-MySQL的安装和管理
    01-pymysql模块的安装
    异常处理
    USACO 2015 Feb Censoring
    玄武密码(bzoj4327)(JSOI2012)
    浅谈AC自动机
    Equation
    JOI五子棋
    浅谈Tarjan
    年轮蛋糕JOI2014Final
  • 原文地址:https://www.cnblogs.com/jostree/p/3703298.html
Copyright © 2011-2022 走看看