LintCode 150. Best Time to Buy a

2017-11-01  本文已影响0人  Andiedie

原题

LintCode 150. Best Time to Buy and Sell Stock II

Description

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example

Given an example [2,1,2,0,1], return 2

解题

给出股票价格的变化,只能每天只能买入或卖出一次,交易总次数不限,求利润最大值。

代码

class Solution {
public:
    /*
    * @param prices: Given an integer array
    * @return: Maximum profit
    */
    int maxProfit(vector<int> &prices) {
        // write your code here
        int minPrice = INT_MAX;
        int res = 0;
        for (auto p : prices) {
            if (p > minPrice) {
                res += p - minPrice;
                minPrice = p;
            } else if (p < minPrice) {
                minPrice = p;
            }
        }
        return res;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读