121. Best Time to Buy and Sell Stock [Easy]

121. Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Constraints:

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Example

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

思路

分析题目

  • 求两数之差最大值
  • 只能高位减低位

那也就是说如果低位比高位大,那这个低位就应该被高位取代

题解

  • 无脑快速AC
    public int maxProfit(int[] prices) {
        ArrayList<Integer> data = new ArrayList<>();
        Arrays.stream(prices).forEach(data::add);
        int left, right, result;
        result = left = 0;
        right = left + 1;
	// 低位要小于高位且高位小于数组最大位数
        while (left < right && right < prices.length) {
	    // 如果当前低位比高位大,那高位应该取代低位位置
            if (prices[left] > prices[right]) {
                left = right;
                right = left + 1;
                continue;
            }
            result = Math.max(result, prices[right] - prices[left]);
            right++;
        }
        return result;
    }
  • 优化
    public int maxProfit(int[] prices) {
        ArrayList<Integer> data = new ArrayList<>();
        Arrays.stream(prices).forEach(data::add);
        int left, right, result;
        result = left = 0;
        right = left + 1;
        while (right < prices.length) {
            if (prices[left] > prices[right])
                left = right;
            else
                result = Math.max(result, prices[right] - prices[left]);
            right++;
        }
        return result;
    }
posted @ 2023-01-11 17:03  AaronTanooo  阅读(31)  评论(0)    收藏  举报