码迷,mamicode.com
首页 > 其他好文 > 详细

99_leetcode_Best Time to Buy and sell Stock

时间:2017-07-09 16:24:57      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:cpp   sign   art   i++   最小   algorithm   ott   ted   tracking   

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

标签:cpp   sign   art   i++   最小   algorithm   ott   ted   tracking   

原文地址:http://www.cnblogs.com/wzjhoutai/p/7141522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!