flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理

分析

难度 易

来源

https://leetcode.com/problems/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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [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.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

解答

 1 package LeetCode;
 2 
 3 public class L121_BestTime2BuyAndSellStock {
 4       public int maxProfit(int[] prices) {
 5         int orginLen=prices.length;
 6         if(orginLen<2)
 7             return 0;
 8         int min=prices[0];
 9         int profit=0;
10         for(int i=1;i<prices.length;i++){
11             if(prices[i]<min)
12                 min=prices[i];
13             if (prices[i] > prices[i - 1])//减少不必要的Math.max运算
14                 profit=Math.max(profit,prices[i]-min);
15         }
16         return profit;
17     }
18     public static void main(String[] args){
19         L121_BestTime2BuyAndSellStock l121=new L121_BestTime2BuyAndSellStock();
20         int[] prices={7,1,5,3,6,4};
21         long timer1=System.currentTimeMillis();
22         System.out.println(l121.maxProfit(prices));
23         long timer2=System.currentTimeMillis();
24     }
25 }

 

 

posted on 2018-11-05 10:58  flowingfog  阅读(119)  评论(0编辑  收藏  举报