121. Best Time to Buy and Sell Stock

    xiaoxiao2021-03-25  111

    Say you have an array forwhich the ith element is the price of a given stock on day i.

     If you were only permitted tocomplete 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 (not7-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 transactionis done, i.e. max profit = 0.

        翻译:有一整形数组,数组的a[i]代表第i天股票的价格,只能买卖一次,求获利最大值。这题不难,只用求出最小值和最大值的差就行了。但是股票在卖之前必须要买。具体代码如下:

    public class Solution {

        public int maxProfit(int[] prices) {

            int result=0;

            if(prices.length==0) {

                return 0;

            }

               int min=prices[0];

               for(int i=0;i<prices.length;i++){

                     if(prices[i]>=min){

                          if(prices[i]-min>result){

                                result=prices[i]-min;

                          }

                     }else{

                          min=prices[i];

                     }

               }

               return result;

        }

    }

    转载请注明原文地址: https://ju.6miu.com/read-19618.html

    最新回复(0)