1. 程式人生 > >leetcode 121. Best Time to Buy and Sell Stock

leetcode 121. Best Time to Buy and Sell Stock

clas which style ces pre max des sign har

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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 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

In this case, no transaction is done, i.e. max profit = 0.

動態規劃,先找到子問題。

只有一個值,那麽就是返回0

當有兩個值時,那麽就是第二個值 - 第一個值(如果大於0的話)

當有三個值時,是第三個值 - min(第二個值,第一個值)

當有n的值時,是第n個值 - min (前n-2個值的min,第n-1個值)

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
3 int n=prices.length; 4 if(n==0){ 5 return 0; 6 } 7 int min=prices[0]; 8 int profit=0; 9 for (int i=1;i<n;i++){ 10 min=Integer.min(min,prices[i-1]); 11 int temp=prices[i]-min; 12 if (temp>profit){
13 profit=temp; 14 } 15 } 16 if (profit>=0){ 17 return profit; 18 } 19 else { 20 return 0; 21 } 22 } 23 }

leetcode 121. Best Time to Buy and Sell Stock