Leetcode——121. Best Time to Buy and Sell Stock
題目原址
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
題目描述
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)
Example2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
解題思路
翻譯:
你有一個(gè)數(shù)組,數(shù)組中的數(shù)是當(dāng)天的股票價(jià)格,如prices[1] = 10,表示第2天的股票價(jià)格為10
你最多有一次交易的機(jī)會(huì)(即:只能買一次股票,賣一次股票)設(shè)計(jì)一個(gè)算法找出交易的最大利潤。
- 這道題使用Kadane’s algorithm(Kadane算法)實(shí)現(xiàn),Kadane是卡內(nèi)基梅隆大學(xué)的教授,而該算法是為了解決最大子序列的和(maximum subarray)提出的。
- Leetcode上面有很多求最大子序列和的問題,這種題應(yīng)該算是一個(gè)類型的。
- 解決該題的方法還是很簡單的:
- 判斷當(dāng)當(dāng)前最大利益 + 當(dāng)前的元素-當(dāng)前元素的前一個(gè)元素的值是否是負(fù)數(shù),如果是負(fù)數(shù),就說明已經(jīng)賠沒了,不能買當(dāng)前股票的前面的股票了,所以當(dāng)前的利益為0。如果值為正數(shù),則還可以往下遍歷。
- 每次更改當(dāng)前利益之后,都要判斷當(dāng)前利益與總利益之間的大小,保證總利益永遠(yuǎn)最大。
AC代碼
class Solution {public int maxProfit(int[] prices) {int max_ending_here = 0;int max_so_far = 0;for(int i = 1; i < prices.length; i++) {max_ending_here = Math.max(0, prices[i] - prices[i-1] + max_ending_here);max_so_far = Math.max(max_so_far, max_ending_here);}return max_so_far; } }感謝
https://discuss.leetcode.com/topic/19853/kadane-s-algorithm-since-no-one-has-mentioned-about-this-so-far-in-case-if-interviewer-twists-the-input/3
總結(jié)
以上是生活随笔為你收集整理的Leetcode——121. Best Time to Buy and Sell Stock的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机字体为什么会模糊,电脑字体很模糊怎
- 下一篇: 爱到尽头 覆水难收