日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode——121. Best Time to Buy and Sell Stock

發(fā)布時(shí)間:2024/3/12 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode——121. Best Time to Buy and Sell Stock 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目原址

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。