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;
        }
    };
  • 相关阅读:
    面向对象简介
    方法简述
    数组,排序方法
    循环结构
    类型转换、流程控制
    基本数据类型、变量、运算符
    基础语法、进制转换、环境配置
    python学习之字典
    python学习之字符串
    jmeter控制器
  • 原文地址:https://www.cnblogs.com/fengxw/p/6061591.html
Copyright © 2011-2022 走看看