题目:
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).
来源:http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
思路:
首先注意到以下几点:
1. 可以在一天进行很多的交易(不过这道题其实每天最多交易2次就够了,一次卖出和一次买入)
2. 在卖股票之前首先得有股票在手里。
由于给了所有n天的股票市值,我们可以简单的处理此问题:如果下一天的股票价值比这一天高,我们买入股票(如果没有股票的话);如果下一天的股票价值比这一天低,我们就在当天卖出股票(如果有股票的话), 相当于能够获得所有的上升子序列的收益。
而且,对于一个序列,比如:5,1,2,4,3 中来说,对于两种操作方案:一,在1买入,4卖出;
二,在1买入,2卖出同时买入,4卖出;(贪心法,低进高出,把所有正的价格差价相加起来。)
这两种操作下,收益是一样的。
C++ AC代码:
class Solution {
public:
int maxProfit(vector<int> &prices) {
if ( prices.size() <= 1)
return 0;
int totalprofit = 0;
for ( int i = 1; i < prices.size(); ++i ){
int profit = prices[i] - prices[i - 1];
if (profit > 0 ) totalprofit += profit;
}
return totalprofit;
}
};
运行时间:48ms
测试代码:
/*
*作者:RogerKing
*邮箱: jin_tengfei@163.com
*日期:2014-03-21-19.03
*/
#include <iostream>
#include <vector>
using namespace std;
int maxProfit(vector<int> &prices)
{
if ( prices.size() <= 1)
return 0;
int totalprofit = 0;
for ( int i = 1; i < prices.size(); ++i )
{
int profit = prices[i] - prices[i - 1];
if (profit > 0 ) totalprofit += profit;
}
return totalprofit;
}
int main(int argc, char *argv[])
{
int price[5] = {5,1,2,4,3};
vector<int> prices(price,price+5);
cout <<"一段时间内每日的价格:";
for (int i = 0; i < prices.size(); ++i)
{
cout << prices[i]<<" ";
}
cout <<endl ;
cout <<"利润:"<< maxProfit(prices);
return 0;
}