题目
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).
题目大意:
假设你有一个数组,其中第i 个元素是第i天给定股票的价格。
设计一个算法来找到最大的利润。您可以根据需要完成尽可能多的交易(即,购买一次并多次出售股票)。但是,您可能不会同时从事多个交易(即,您必须在再次购买之前先出售该股票)。
解题思路
最低点买入,最高点卖出,所以只需要计算增长过程中相关联的最低点到最高点差值即可
class Solution {
public:
int maxProfit(vector<int>& prices) {
int total = 0;
for(int i =1; i < prices.size(); ++i)
{
if (prices[i-1] < prices[i])
{
total += prices[i]-prices[i-1];
}
}
return total;
}
};
网友评论