Leetcode Best Time to Buy and Sell Stock 2

来源:互联网 发布:呼死你在淘宝上叫什么 编辑:程序博客网 时间:2024/06/01 07:45

/************************************************************************
*
* 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 <iostream>#include <vector>using namespace std;int maxProfit(vector<int> &price){    int begin = 0, end = 0, max = 0;    //这里添加了两个标志,判断股票状态    bool up = false, down = false;    for (int i = 1; i<price.size(); i++) {        if (price[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<int>price = { 23,24,27,18,23,19,31 };    cout << maxProfit(price) << endl;}
0 0
原创粉丝点击