best-time-to-buy-and-sell-stock[股票的涨跌]

题目描述 I

Say you have an array for which the i th 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.

  • 思路
    贪心算法,初始化一个最小值,依次遍历。
    若大于当前值则更新最小值;否则更新最大收益。
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length < 2)
            return 0;
        
        int ans = 0;
        int minV = prices[0];
        for(int i=1; i prices[i]){
                minV = prices[i];
            }else{
                ans = Math.max(ans, prices[i]-minV);
            }
        }
        return ans;
    }
}

题目描述 II

Say you have an array for which the i th 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).

  • 思路
    求若干天最大收益(首先要买到股票才能卖出获得利润),因此当只有一天时利润为0;其他情况是在一个递增区间内,最低价买入最高价卖出。
    而在一个递增区间内,只要上一天比下一天价格低,就可以获得这两天的差价。顺序遍历求总和即可
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length < 2)
            return 0;
        
        int ans = 0;
        
        for(int i=1; i

题目描述III

Say you have an array for which the i th 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).

  • 思路
    求最多两次交易的最大利润。
    假如只进行1次交易的话会更简单一些:用sell1表示初始时身上的净利润为0,buy1用于存放最便宜股价的价格。一个循环表示时间一天天推移,第一天时buy1记录下第一天买入股票的最低花费,之后每进入新的一天(今天),就用buy1表示前些天最便宜的股价,sell1保存了前些天买入最便宜股票之后再在卖出股票的最大利润。新的一天到来,再用buy1继续记录最低股价,再计算出在今天抛售那个最低价股票后的利润,如果这个利润比之前保存的sell1高,那就更新sell1,否则,sell1不变。如此循环下去,到最后一天结束,sell1就记录了一次交易的最大利润。
    进行多次交易的道理是可以类推的。
    参考链接
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length <= 1)
            return 0;
        
        int buy1 = Integer.MIN_VALUE;
        int sell1 = 0;
        
        int buy2 = Integer.MIN_VALUE;
        int sell2 = 0;
        
        for(int i=0; i

你可能感兴趣的:(best-time-to-buy-and-sell-stock[股票的涨跌])