zoukankan      html  css  js  c++  java
  • Leetcode-121 Best Time to Buy and Sell Stock

    #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.

    题解:关键点在于随着prices的遍历,更新成本cost和计算prices[i]和cost的差值。初始cost设置为最大int整数,profit初始为0,随着遍历的进行,计算prices[i]和当前cost的差值,如果差值小于0,则更新cost值为prices[i],如果差值大于当前profit,则更新profit的值为当前差值。

    class Solution {                                                        
    public:
        int maxProfit(vector<int>& prices) {
        int cost = 2147483647;
        int profit = 0;
        for (int i = 0;i<prices.size();++i)
        {
            int p = prices[i] - cost;
            if (p > profit)
                profit = p;
            if (prices[i] < cost)
                cost = prices[i];
        }
        return profit;
    }
    };              
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if(prices.size()<2)
                return 0;
            int cost=prices[0];
            int profit=0;
            for(int i=1;i<prices.size();i++)
            {
                cost=min(prices[i],cost);
                profit=max(profit,prices[i]-cost);
            }
            return profit;
        }
    };
  • 相关阅读:
    Redis常见问题及解决方案
    Maven构建报错问题解决
    Nginx正向代理设置
    Linux下限制某程序CPU占用
    Linux-flock文件锁的使用
    Python将print输出内容保存到指定文件中
    使用Zabbix官方模板监控Redis运行状况
    阿里云ossfs配置
    docker swarm 集群及可视化界面的安装及配置
    http://www.fx114.net/qa-24-116329.aspx
  • 原文地址:https://www.cnblogs.com/fengxw/p/6061591.html
Copyright © 2011-2022 走看看