121. Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝全屏海报怎么设置 编辑:程序博客网 时间:2024/05/20 17:41

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;

    }

}

0 0