121. 买卖股票的最佳时机

题目描述

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.

代码实现

class Solution {
public:
    int maxProfit(vector<int> &prices) {

    	int size = prices.size();
    	if(size == 0 ||size == 1)
    		return 0;
        //极端情况下,不买也不卖,什么也不做
    	int ret = 0;
    	int minPrice = prices[0];
        //动态规划,流式处理
    	for(int i = 1;i<size;i++)
        {
            
    		if(prices[i] < minPrice)
    			minPrice = prices[i];
    		else 
			{
				if(prices[i] - minPrice > ret)
					ret = prices[i] - minPrice;
			}
    	}
    	return ret;      
    }
};

posted on 2021-04-04 18:11  朴素贝叶斯  阅读(33)  评论(0编辑  收藏  举报

导航