Best Time to Buy and Sell Stock1,2

题目地址:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/#/description

题目:
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

解题思路:这道题主要就是维持并更新两个变量:min和rst。首先更新min,然后更新rst。
这里会有followup:
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).

代码:

public int maxProfit(int[] prices) {
    if(prices == null || prices.length <= 1){
        return 0;
    }
    int min = prices[0];
    int rst = Integer.MIN_VALUE;
    for(int i = 1; i <= prices.length - 1; i++){
        min = Math.min(min, prices[i]);
        rst = Math.max(rst, prices[i] - min);
    }
    return rst;
}

Follow up:



public int maxProfit(int[] prices) {
    if(prices == null || prices.length <= 1){
        return 0;
    }
    int max = 0;
    for(int i = prices.length - 1; i > 0; i--){
        int diff = prices[i] - prices[i - 1];
        max += diff > 0 ? diff : 0;
    }
    return max;
}

这里有一个follow up:
如果给你100美元,那么问你卖出去的最大收益。

public int maxProfix(int[] prices, int cash){
    if (prices == null || prices.length < 2){
        return cash;
    }

    int minValue = Integer.MAX_VALUE;
    int maxProfix = 0;

    for (int i = 1; i < prices.length; i++) {
        if (minValue > prices[i - 1]){
            minValue = prices[i - 1];
        }
        int numOfStocks = cash / minValue;
        maxProfix = Math.max(maxProfix, (prices[i] - minValue) * numOfStocks);
    }
    return maxProfix < 0 ? cash : cash + maxProfix;
}








Comments

Popular Posts