题目:
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天的股票交易价格。
设计一个算法求出股票买卖最大利润。你想进行多少次交易就进行多少次交易(即随意买卖多少次)。但是,你同一时间不能进行多次交易(也就是说,你必须先卖股票才能买股票)。
思路:
嗯,股票买卖系列之二。这个比上题还要简单,随意买卖多少次。就是说,只要找出后一个元素比前一个元素大的,求其差相加即可。(虽然题目中说,你必须先卖股票才能买股票,然而这对设计算法并没有什么卵用:如果后一天比前一天大,你后一天不卖是了.....你只要在后一天价格比前一天价格低时,卖出前一天股票;后一天价格比前一天价格高时,买入股票或者持有股票不卖即可)。
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size()<2){
return 0;
}
int profit=0;
for(int i=0;i<prices.size()-1;i++){
if(prices[i+1]>prices[i])
profit+=prices[i+1]-prices[i];
}
return profit;
}
};