首页 > 代码库 > leetcode 121. Best Time to Buy and Sell Stock

leetcode 121. 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.

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