Leetcode:Best Time to Buy and Sell Stock II

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

分析:貪心算法。若是能夠交易屢次,那麼只要當前一個價格比前一個價格高咱們就能夠交易,最終能夠得到最大利益。代碼以下:code

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int maxPro = 0;
        
        for(int i = 1; i < prices.size(); i++){
            if(prices[i] > prices[i-1]) maxPro += prices[i] - prices[i-1];
        }
        
        return maxPro;
    }
};
相關文章
相關標籤/搜索