摘要:求可能的最大利潤題目給了兩個例子最大利潤就是進價為,賣價為的時候,利潤為在這個案例中,進價一直高于售價,所以無法成交,返回。主要注意一下,先買入才能賣出賣價一定要比買入價格高才能成交就可以了。
題目詳情
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.
這道題描述的意思就是,給定一個數(shù)組prices,里面的第i個元素就是商品第i天的價格。我們要選擇某天買入,某天賣出(賣出操作肯定在買入操作之后)。求可能的最大利潤理解題目給了兩個例子
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
最大利潤就是進價為1,賣價為6的時候,利潤為5.
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
在這個案例中,進價一直高于售價,所以無法成交,返回0。
這道題理解了其實是比較簡單的。主要注意一下,先買入才能賣出、賣價一定要比買入價格高才能成交就可以了。
解法public int maxProfit(int[] prices) { int maxProfit = 0; int minBuyPrice = 0; if(prices.length <= 1){ return 0; } minBuyPrice = prices[0]; for(int i=1;imaxProfit){ maxProfit = curPrice - minBuyPrice; } } return maxProfit; }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/68233.html
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 (i.e., buy on...
摘要:分析因為當(dāng)前日期買賣股票會受到之前日期買賣股票行為的影響,首先考慮到用解決。所以我們可以用兩個數(shù)組分別記錄當(dāng)前持股跟未持股的狀態(tài)。 Best Time to Buy and Sell Stock with Cooldown Say you have an array for which the ith element is the price of a given stock on ...
摘要:示例輸入輸出解釋對應(yīng)的交易狀態(tài)為買入賣出冷凍期買入賣出思路這道題使用動態(tài)規(guī)劃。狀態(tài)表示當(dāng)天休息能夠獲得的最大價值,表示當(dāng)天持有股票能夠獲得的最大價值,表示當(dāng)天持有股票能夠獲得的最大價值。 Description Say you have an array for which the ith element is the price of a given stock on day i. ...
摘要:關(guān)鍵字,,算法,,動態(tài)規(guī)劃,上關(guān)于主題的題目有四個這四個題目難度依次遞增。其中第四個問題是尋求一個通解,在給定和最大買賣次數(shù)的情況下,求最大收益。首先大致的解題方向是動態(tài)規(guī)劃,這個應(yīng)該不難想到。之后就是怎么找到狀態(tài),怎么列狀態(tài)轉(zhuǎn)移方程。 關(guān)鍵字:leetcode,Best Time To Buy And Sell Stock,算法,algorithm,動態(tài)規(guī)劃,dynamic prog...
摘要:題目要求有一個整數(shù)數(shù)組,每一位上的值代表那一天的股票價格?,F(xiàn)在假設(shè)最多能夠進行次交易,問最大的收入是多少思路和代碼這里采用了動態(tài)編程的思想。 題目要求 Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find t...
閱讀 1152·2021-11-24 09:39
閱讀 1610·2021-11-18 13:18
閱讀 2701·2021-11-15 11:38
閱讀 1924·2021-09-26 09:47
閱讀 1740·2021-09-22 15:09
閱讀 1713·2021-09-03 10:29
閱讀 1619·2019-08-29 17:28
閱讀 3121·2019-08-29 16:30