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 };
  • 相关阅读:
    距离某天还有多久
    U3D各键值说明
    一些比较重要的函数
    U3D功能脚本备忘
    沟边
    渲染排序
    字符串转整数备录
    沟边
    U3D优化
    Unity中的四个路径
  • 原文地址:https://www.cnblogs.com/jostree/p/3703298.html
Copyright © 2011-2022 走看看