题目:
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).
代码:
class Solution { public: int maxProfit(vector<int>& prices) { if ( prices.size()==0 ) return 0; int sum_profits = 0, pre_price = prices[0]; for ( size_t i = 1; i < prices.size(); ++i ) { sum_profits += (prices[i]>pre_price) ? prices[i]-pre_price : 0; pre_price = prices[i]; } return sum_profits; } };
tips:
Greedy算法。
核心算法:如果当天的价格比前一天高,sum_profits就累加上当天的利润与前一天利润的差值(即昨天买,今天买);如果当天的价格比昨天低,则不更新sum_profits(即今天买,今天卖)。
时间: 2024-10-05 20:01:12