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;
        }
    };
  • 相关阅读:
    [C#] 等待启动的进程执行完毕
    C# 、winform 添加皮肤后(IrisSkin2) label设置的颜色 无法显示
    Mysql 备份
    Mysql 慢查询日志配置
    Mysql 忘记密码处理配置
    PHP-FPM 慢执行日志、网站隔离配置
    PHP-FPM 设置多pool、配置文件重写
    Nginx 代理配置
    Nginx 301与302配置
    Nginx URL跳转
  • 原文地址:https://www.cnblogs.com/fengxw/p/6061591.html
Copyright © 2011-2022 走看看