99_leetcode_Best Time to Buy and sell Stock

Posted wzjhoutai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了99_leetcode_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

1:遍历数组;2:每个数字获得该数字之前的最小的数字,并与当时保存的最大值相比較

    int maxProfit(vector<int> &prices)
    {
        if(prices.size() <= 1)
        {
            return 0;
        }
        
        int maxValue = 0;
        int minPrice = prices[0];
        int size = (int)prices.size();
        
        for(int i = 1; i < size; i++)
        {
            if(prices[i] > minPrice)
            {
                maxValue = (maxValue > prices[i] - minPrice ? maxValue : prices[i] - minPrice);
            }
            else
            {
                minPrice = prices[i];
            }
        }
        
        return maxValue;
    }




以上是关于99_leetcode_Best Time to Buy and sell Stock的主要内容,如果未能解决你的问题,请参考以下文章

抓jsoup_02_数据

______more time ,the scientists will be able to work out a good solution to the problem

24.leetcode121_best_time_to_buy_and_sell_stock

121. Best Time to Buy and Sell Stock

leetcode第一刷_Best Time to Buy and Sell Stock

Illegal instant due to time zone offset transition (Asia/Shanghai)_夏令时问题