国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Leetcode 121. Best Time to Buy and Sell Stock

2019-11-14 09:44:21
字體:
供稿:網(wǎng)友

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.

s思路: 1. 低價買入,高價賣出!從左往右遍歷,當遇到開始增加的位置就是可能的低價位,然后遍歷后面的高價位,找最大的差值! 2. 這道題有意思的地方在于:lowprice是目前為止的最小值,后面遇到的值和這個最小值的差值即為目前位置的最大值,兩個變量就可以模擬這個動態(tài)的過程:lowprice為目前最小值,profit為目前最大profit:而profit=max(profit,prices[i]-lowprice).

class Solution {public: int maxProfit(vector<int>& prices) { // int profit=0; int lowprice=INT_MAX; for(int i=0;i<prices.size();i++){ lowprice=min(lowprice,prices[i]); profit=max(profit,prices[i]-lowprice); } return profit; }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 大姚县| 旺苍县| 马山县| 垦利县| 巍山| 莆田市| 五指山市| 怀仁县| 诸暨市| 海伦市| 泽州县| 岢岚县| 茂名市| 门源| 浮山县| 龙陵县| 兴城市| 延吉市| 中西区| 永丰县| 侯马市| 乌恰县| 德安县| 财经| 贡嘎县| 徐水县| 万荣县| 焉耆| 土默特右旗| 赞皇县| 临猗县| 紫金县| 沭阳县| 金昌市| 怀集县| 邢台县| 滁州市| 阳朔县| 吉安市| 宝清县| 金塔县|