码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 121. Best Time to Buy and Sell Stock

时间:2017-07-03 18:04:57      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:inpu   case   one   nbsp   第一个   mos   ++   his   turn   

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

标签:inpu   case   one   nbsp   第一个   mos   ++   his   turn   

原文地址:http://www.cnblogs.com/sure0328/p/7112174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!