本文共 1543 字,大约阅读时间需要 5 分钟。
/************************************************************************
* * 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). * **********************************************************************/ 题目解析:例如股票的变化如下 23,24,27,18,23,19,31 这里我们可以随意操作股票,因此,只要将股票下降的前一天,立即收回股票, 明天继续入手。 因此可分在第一天入手,第三天出手 第四天入手,第五天出手 第六天入手,第七天出手// Author : yqtao// Date : 2016-6.19// Email :yqtao@whu.edu.cn#include "stdafx.h"#include#include using namespace std;int maxProfit(vector &price){ int begin = 0, end = 0, max = 0; //这里添加了两个标志,判断股票状态 bool up = false, down = false; for (int i = 1; i price[i - 1] && up == false) { // goes up begin = i - 1; up = true; down = false; } if (price[i] < price[i - 1] && down == false) { // goes down end = i - 1; down = true; up = false; max += (price[end] - price[begin]); } } // 考虑边界条件 if (begin < price.size() && up == true) { end = price.size() - 1; max += (price[end] - price[begin]); } return max;}int main(){ vector price = { 23,24,27,18,23,19,31 }; cout << maxProfit(price) << endl;}
转载地址:http://vsdoi.baihongyu.com/