121. Best Time to Buy and Sell Stock

来源:互联网 发布:数据库实验报告总结 编辑:程序博客网 时间:2024/06/06 07:06

121. Best Time to Buy and Sell Stock

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

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.
Analysis:
这个题是一个先买后卖赚差价的问题。
低价买高价卖,但是低价必须在高价前边。
假设第i天价格为p(i),我们只需要将其与前i-1天的最低价lowestPrice的差值(p(i)-lowestPrice)和前i-1天的利润差值(sell-buy)做对比。如果差值增大,将其设为新的sell和buy价格即可。
提示:lowestPrice和buy值很有可能是一个数,p(i)和sell也可能是同一个数,所以并非每次改变都会把sell和buy值全部覆盖,这里我们不用去管它。
Source Code(C++):

#include <iostream>#include <vector>using namespace std;/*****************************遍历法找出最大值,时间复杂度O(n2),这样会超时*******************************************//*class Solution {public:    int maxProfit(vector<int>& prices) {        int maxProfit=0, tempProfit=0;        for (int i=prices.size()-1; i>=0; i--) {            for (int j=i; j>=0; j--) {                tempProfit = prices.at(i)-prices.at(j);                if (maxProfit<tempProfit) {                    maxProfit = tempProfit;                }            }        }        return maxProfit;    }};*/class Solution {public:    int maxProfit(vector<int>& prices) {        if (prices.empty()) {            return 0;        }        int buy=prices.at(0), sell=prices.at(0), lowestPrice=prices.at(0);        for (int i=1; i<prices.size(); i++) {            if (prices.at(i)-lowestPrice > sell-buy) {                buy=lowestPrice;                sell=prices.at(i);            }            if (prices.at(i)<lowestPrice) {                lowestPrice=prices.at(i);            }        }        return sell-buy;    }};int main() {    Solution sol;    vector<int> v;    v.push_back(5);    v.push_back(2);    v.push_back(8);    v.push_back(7);    v.push_back(9);    cout << sol.maxProfit(v);    return 0;}
0 0