题目描述
假设你有一个数组,其中第i个元素表示某只股票在第i天的价格。设计一个算法来寻找最大的利润。你可以完成任意数量的交易(例如,多次购买和出售股票的一股)。但是,你不能同时进行多个交易(即,你必须在再次购买之前卖出之前买的股票)。
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).
题目分析:
要寻找最大利润,则每天不能亏钱,即数组要是当天的价格不能低于前一天的价格并且每次股票涨的时候都进行了交易。
代码如下:
1 int maxProfit(vector<int>& prices) { 2 int sum = 0; 3 for(int i = 1;i < prices.size();i++) 4 { 5 if(prices[i - 1] < prices[i]) 6 sum = sum + prices[i] - prices[i - 1]; 7 } 8 return sum; 9 }