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

    解析

    //Best Time to Buy and Sell Stock
    class Solution_121 {
    
    		//分析一下价格曲线的不同走势对应的不同操作:
    		//上升沿:此时都是收益的,我们需要判断现在的价格减去之前保留的最低的价格是否大于之前计算的最大收益即可。
    		//下降沿:此时收益在降低,我们只需要判断新的价格是不是比之前保留的最低价格还要低即可。
    
    	//1. 从后往前算, 因为卖肯定要比买之后,从后往前找到最大值,和当前值做差,差值的最大值就是获取的最大利润 
    	//2. 找到第i天之前的最小值,然后prices[i] - min与最大收益maxprofit比较
    	// 从前或者从后逆序都可以
    
    public:
    	int maxProfit_1(vector<int>& prices) {   //Time Limit Exceeded
    
    		int ret = 0;
    
    		for (int i = 0; i < prices.size()-1;i++)
    		{
    			for (int j = i+1; j < prices.size();j++)
    			{
    				if (prices[j]-prices[i]>=0)
    				{
    					ret = max(ret, prices[j] - prices[i]);
    				}
    			}
    		}
    		return ret;
    	}
    
    	int maxProfit(vector<int>& prices) {
    
    		if (prices.size()<=1)
    		{
    			return 0;
    		}
    		int max_profit = 0;
    		int cur_profit = 0;
    		int cur_min = prices[0];
    		for (int i = 1; i < prices.size();i++)
    		{
    			if (prices[i]<cur_min)
    			{
    				cur_min = prices[i]; //更新当前最小值
    			}
    			cur_profit = prices[i] - cur_min;
    			if (cur_profit>max_profit)
    			{
    				max_profit = cur_profit;
    			}
    		}
    		return max_profit;
    	}
    };
    

    题目来源

  • 相关阅读:
    机器学习中规则化和模型选择知识
    关于arcengine权限的设置
    arcengine 实现调用arctoolbox中的dissolove
    基于手机令牌的屏保软件设计与实现
    RelativeLayout中最底的View一个View.layout_marginBottom无效
    Citrus Engine简单Demo
    Java菜鸟学习笔记(23)--继承篇(二):继承与组合
    uva 579 ClockHands 几何初接触 求时针与分针的夹角
    OpenCV中GPU函数
    html监听,键盘事件
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8192275.html
Copyright © 2020-2023  润新知