27. Best Time to Buy and Sell Stock && Best Time to Buy and Sell Stock II && Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock

(onlineJudge: https://oj.leetcode.com/problems/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.

注意: 限制条件: 先买后卖(不同天)。

思想: 买了后,1. 若以后价格不变,不买不卖。 1. 更价格低,重新买。2. 价格升高,假定抛售,更新一下利润值。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int buy = 0x7fffffff, maxProfile = 0;
        for(int i = 0; i < prices.size(); ++i) {
            if(prices[i] == buy) continue;
            if(prices[i] < buy) { buy = prices[i]; continue; }
            else maxProfile = max(maxProfile, prices[i]-buy);
        }
        return maxProfile;
    }
};

Best Time to Buy and Sell Stock II

(onlineJudge:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

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).

思想:求出所有非递减序列两端绝对值之和。我贴在 leedcode 的代码和证明:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n = prices.size();
        if(n == 0) return 0;
        int start = 0, profile = 0;
        for(int i = 1; i < n; ++i) {
            if(prices[i] < prices[i-1]) {
                profile += prices[i-1] - prices[start];
                start = i;
            }
        }
        profile += prices[n-1] - prices[start];
        return profile;
    }
};
/*********************** *provement ***************/
/*Explain the code I pasted above: 

From left to right I find out every subsequence that not exist decrease. 

such as: l ... k1 ...k2 ... h (l <=...<= k1 <= ... k2 <= ... <= h)

In this sequence: ( k1-l ) + ( h-k2 ) = ( h-l ) - ( k2-k1 ) <= ( h-l ); 

So (h - l) will be the maximum profit in this days.

Another case:

L1 ...d1... H1 K2 ...k... K3 L2 ...d2... H2 (L1 <=... H1 > K2 >=...k >=... K3 > L2 <=... H2 )

K2 ... K3 is not exist increase sequence.

then for any k in that position,

( k-d1 ) + ( d2-k ) <= ( K2-L1 ) + ( H2-K3 ) < ( H1-L1 ) + ( H2-L2 ) 

In my code, variant "start" is the start of every no decrease sequence.*/

A little Adjustment.

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int start = 0, profile = 0;
        for(size_t i = start+1; i < prices.size(); ++i) {
            if(prices[i] < prices[i-1]) {
                profile += prices[i-1] - prices[start];
                start = i;
            }
            else if(i+1 == prices.size())
                profile += prices[i] - prices[start];
        }
        return profile;
    }
};

Best Time to Buy and Sell Stock III

(onlineJudge: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

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 at most two transactions.

Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

思想:动态规划。 记录下从各位置(含)开始之前的最大利润和此时开始到最后的最大利润。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        vector<int> preProfile(prices.size()+2, 0), postProfile(prices.size()+2, 0);

        int minPrice = 0x7fffffff;
        for(size_t i = 1; i <= prices.size(); ++i) {
            minPrice = min(minPrice, prices[i-1]);
            preProfile[i] = max(prices[i-1] - minPrice, preProfile[i-1]);
        }

        int maxPrice = 0;
        for(int i = prices.size(); i >= 1; --i) {
            maxPrice = max(maxPrice, prices[i-1]);
            postProfile[i] = max(maxPrice - prices[i-1], postProfile[i+1]);
        }

        int maxProfile = 0;
        for(size_t i = 1; i <= prices.size(); ++i)
            maxProfile = max(maxProfile, preProfile[i] + postProfile[i]);
        return maxProfile;
    }
};
时间: 2024-11-04 23:48:31

27. Best Time to Buy and Sell Stock && Best Time to Buy and Sell Stock II && Best Time to Buy and Sell Stock III的相关文章

309. Best Time to Buy and Sell Stock with Cooldown

/* * 309. Best Time to Buy and Sell Stock with Cooldown * 2016-7-4 by Mingyang * http://buttercola.blogspot.com/2016/01/leetcode-best-time-to-buy-and-sell.html * *1. Define States * *To represent the decision at index i: *buy[i]: Max profit till inde

Leetcode 贪心 Best Time to Buy and Sell Stock

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Best Time to Buy and Sell Stock Total Accepted: 13234 Total Submissions: 43145 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

Best Time to Buy and Sell Stock with Cooldown -- LeetCode

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) wit

Java for LeetCode 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. 解题思路

[LeetCode] Best Time to Buy and Sell Stock 合集

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 给出股票每一天的价格,求解只做一次交易的最佳收益方案. 思路是首先建立一个存储股票每天差价的数组 diff[],其中 diff[i] = prices[i] - prices[i - 1],这样原问题就变成了最大连续子数组和的问题. int maxProfit(int* prices, int pricesSize) { if (!pricesSize) return 0

Buy and sell stocks 总结

buy and sell stocks 在leetcode现在总共有5 道题. Best Time to Buy and Sell Stock 这道题是基础,只能transaction一次,所以我们用 Best Time to Buy and Sell Stock II 这道题表示可以一直transaction,所以只需要下一次比上一次高,那就加一次. Best Time to Buy and Sell Stock with Cooldown 这道题属于进化版, 参考大神的解释:Best tim

Asia Stock Exchanges[z]

Asia Stock Exchanges July 7, 2009 This article is to summarise the trading rules of some Asia stockexchanges. Those rules are very important to know if we need to developany trading system against those exchanges. 1. Hong Kong Stock Exchange 1.1 Orde

The World&#39;s Top 15 Stock Exchanges by Domestic Market Capitalization

 The World's Top 15 Stock Exchanges by Domestic Market Capitalization in 2008 4 Euronext Belgium, France, Holland, Portugal 2,869[1] 5 London Stock Exchange United Kingdom 2,796[1] 6 Shanghai Stock Exchange China 2,704[1] 7 - 13 Australian Securities

POJ 2827 Buy Tickets(排队问题,线段树应用)

POJ 2827 Buy Tickets(排队问题,线段树应用) ACM 题目地址:POJ 2827 Buy Tickets 题意: 排队买票时候插队. 给出一些数对,分别代表某个人的想要插入的位置Pos_i和他的Val_i,求出最后的队列的val顺序. 分析: 也是一道很巧妙的题目. 刚开始天真的以为sort一下就行了.wa了一发后发现我错了... 原来可以很巧妙的用线段树做.由于某个人想要插入posi位置,插入后他就在posi位置上了,但是可能其他人会插到他前面来,他的位置就会变成[在他后面