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

149. Best Time to Buy and Sell Stock【medium】

时间:2018-02-04 20:59:10      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:null   color   它的   sel   public   int   允许   value   for   

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

Given array [3,2,3,1,2], return 1.

 

题意

假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

 

解法一:

 1 class Solution {
 2 public:
 3     /**
 4      * @param prices: Given an integer array
 5      * @return: Maximum profit
 6      */
 7     int maxProfit(vector<int> &prices) {
 8         if (prices.empty()) {
 9             return 0;
10         }
11         int i = prices.size() - 1;
12         int ans = 0;
13         int maxp = prices[i];
14         for (--i; i >= 0; --i){
15             ans = max(ans, maxp - prices[i]);
16             maxp = max(maxp, prices[i]);
17         }
18         return ans;
19     }
20 };

参考@NineChapter 的代码

 

解法二:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if (prices == null || prices.length == 0) {
 4             return 0;
 5         }
 6 
 7         int min = Integer.MAX_VALUE;  //just remember the smallest price
 8         int profit = 0;
 9         for (int i : prices) {
10             min = i < min ? i : min;
11             profit = (i - min) > profit ? i - min : profit;
12         }
13 
14         return profit;
15     }
16 }

参考@NineChapter 的代码

 

149. Best Time to Buy and Sell Stock【medium】

标签:null   color   它的   sel   public   int   允许   value   for   

原文地址:https://www.cnblogs.com/abc-begin/p/8413876.html

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