LeetCode(42)-Best Time to Buy and Sell Stock(卖股票)

时间:2023-03-09 01:32:55
LeetCode(42)-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.

思路:

  • 题意给定一个数组prices,每一个值prices[i]是第i天的股价,要求只能买入和卖出一次,求出最大的获益
  • 首先买入一定在卖出之前,所以要同步更新最小股价,然后最大利润,用一个变量代替最小的股价,一个值来代替最大利润,注意最大利润是负数的情况
  • -

代码:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <= 1){
            return 0;
        }
        int minPrice = prices[0];
        int maxProfit = prices[1] - prices[0];
        for(int i = 2; i < prices.length;i++){
            minPrice = Math.min(minPrice,prices[i-1]);
            maxProfit = Math.max(maxProfit,prices[i]-minPrice);
        }
        if(maxProfit < 0){
            return 0;
        }else{
            return maxProfit;
        }
    }
}