Best Time to Buy and Sell Stock II

来源:互联网 发布:电影天堂软件 编辑:程序博客网 时间:2024/06/16 10:02

Say you have an array for which the ith element is the price of a given stock on dayi.

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)股票购买的原则:低买高卖。

比如说3 2 1 4 5 6 3,那我们在1的时候买,在6 的时候卖出去。

(2)不过编程的时候要注意一些边界条件。

例如

1、1 1 1 1 1

2、4 3 2 1 1

3、1 2 3 4 5

等特殊序列,以及不要数组越界。


#include <iostream>#include <vector>using namespace std;int maxProfit(vector<int> &prices) {int length = prices.size();int buyPrice = 0;int sellPrice = 0;int profit = 0;for(int i=0;i<length-1;i++){if(prices[i] <= prices[i+1]){buyPrice = prices[i];}else{continue;}while(i<length-2 && prices[i] <= prices[i+1]){i++;}if(prices[i] > prices[i+1]){sellPrice = prices[i];profit = profit + sellPrice - buyPrice;continue;}if(i==length-2){if(prices[i] <= prices[i+1]){sellPrice = prices[i+1];profit = profit + sellPrice - buyPrice;i++;continue;}}}return profit;}int main(void){vector<int> prices;prices.push_back(5);prices.push_back(2);prices.push_back(3);prices.push_back(2);prices.push_back(6);prices.push_back(6);prices.push_back(2);prices.push_back(9);prices.push_back(1);prices.push_back(0);prices.push_back(7);prices.push_back(4);prices.push_back(5);prices.push_back(0);cout << "The Profit is " << maxProfit(prices) << endl;system("pause");return 0;}


0 0
原创粉丝点击