leetcode #122 in cpp

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).

Solution:

It is similar to #121. We add all sum of increasing sublist into the profit. 

Code:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty()) return 0;
        int cost = prices[0];
        int price = prices[0];
        int profit = 0;
        for(int i = 1; i < prices.size(); i ++){
            if(prices[i] < price){
                profit+= price - cost; 
                price = prices[i];
                cost = prices[i];
            }else{
                price = prices[i]; 
            }
        }
        profit += price - cost; 
        return profit; 
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章