Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝网app客户端 编辑:程序博客网 时间:2024/06/09 15:49

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

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.


(1)思路比较简单,主要是对于每一个位置求他左边数值的最小值(包括他本身),以后他右边数值的最大值。

(2)循环上面的求解,然后输出一个最大值


#include <iostream>#include <vector>using namespace std;int maxProfit(vector<int> &prices) {size_t len = prices.size();if(len == 0 || len == 1)return 0;vector<int> minLeft(len,0);vector<int> maxRight(len,0);int profit = 0;minLeft[0] = (prices.at(0));maxRight[len-1] = (prices.at(len-1));for(size_t i=1;i<len;i++){if(prices.at(i) < minLeft.at(i-1))minLeft[i] = prices.at(i);elseminLeft[i] = minLeft.at(i-1);}for(int i=len-2;i>=0;i--){if(prices.at(i) > maxRight.at(i+1))maxRight[i] = prices.at(i);elsemaxRight[i] = maxRight.at(i+1);}for(size_t i = 0;i<len-1;i++){int temp = maxRight.at(i+1) - minLeft.at(i);if(temp > profit){profit = temp; }}if(profit <= 0)return 0;return profit;}int main(void){vector<int> prices;prices.push_back(1);prices.push_back(5);prices.push_back(3);prices.push_back(7);prices.push_back(6);prices.push_back(4);prices.push_back(2);prices.push_back(3);cout << maxProfit(prices) << endl;system("pause");return 0;}


0 0