zoukankan      html  css  js  c++  java
  • 122.买卖股票的最佳时机 II

    给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

    设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

    注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

    我的实现: 8ms

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            vector<int>::iterator first = prices.begin();
            vector<int>::iterator last = prices.end();
            int profit = 0;
            if(first == last)
                return 0;
            
            while(first < last-1)
            {
                if(*first < *(first+1))
                {
                    profit += *(first+1) - *first;  
                }
                ++first;
            }
            
            return profit;
        }
    };

    更快实现: 4ms

    int maxProfit(vector<int>& prices) {
            int maxProfit = 0;
            for (int i = 1; i < prices.size(); i++){
                maxProfit += max(prices[i] - prices[i-1], 0);            
            }
            return maxProfit; 
        }
  • 相关阅读:
    28完全背包+扩展欧几里得(包子凑数)
    HDU 3527 SPY
    POJ 3615 Cow Hurdles
    POJ 3620 Avoid The Lakes
    POJ 3036 Honeycomb Walk
    HDU 2352 Verdis Quo
    HDU 2368 Alfredo's Pizza Restaurant
    HDU 2700 Parity
    HDU 3763 CDs
    POJ 3279 Fliptile
  • 原文地址:https://www.cnblogs.com/jimobuwu/p/8961918.html
Copyright © 2011-2022 走看看