700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 121. 买卖股票的最佳时机_面试题63. 股票的最大利润_[找出数组中一个元素和它后面最

121. 买卖股票的最佳时机_面试题63. 股票的最大利润_[找出数组中一个元素和它后面最

时间:2024-06-19 14:45:12

相关推荐

121. 买卖股票的最佳时机_面试题63. 股票的最大利润_[找出数组中一个元素和它后面最

描述

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 one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票

例子

思路

暴力

两个for循环

动态规划

新添加的元素为e,n+1长度的最大收益=max(n长度的最大收益,e-n长度数组中的最小值)

n长度的最大收益:e没有发挥作用

e-n长度数组中的最小值:e发挥作用

答案

java

//方法//arr[i]为i+1->所有的最大的数int[] arr = new int[nums.length];for(int i=arr.length-1;i>=0;i--) {if(i==arr.length-1) arr[i]=0;else arr[i]=Math.max(nums[i+1], arr[i+1]);}int max = 0;for(int i=0; i<nums.length; i++) {max = Math.max(max, arr[i]-nums[i]);}return max;//方法2 不记录后面的最大值了,记录前面的最小值public int maxProfit(int[] nums) {if(nums.length==0) return 0;//到目标为止,最小的买价格int buy=nums[0];int max_=0;for(int i=1; i<nums.length; i++) {max_=Math.max(max_,nums[i]-buy);buy=Math.min(buy,nums[i]);}return max_;}

python

def maxProfit(self, prices: List[int]) -> int:if len(prices)==0:return 0buy = prices[0]profit = 0for i in range(1,len(prices)):profit = max(profit, prices[i]-buy)buy = min(buy,prices[i])return profit

c++

*方法1*int maxProfit(vector<int>& prices) {int profit = 0;for (int i=0; i<prices.size(); i++){int buy = prices[i];for (int j=i+1; j<prices.size(); j++){if (prices[j]-buy>profit)profit = prices[j]-buy;}}return profit;}*方法2*class Solution {public:int maxProfit(vector<int>& prices) {//为空if (prices.size()==0)return 0;//不为空int buy = prices[0];int profit = 0;for (int i=1; i<prices.size(); i++){//buy为~i-1数组中的最小值,profit为~i-1数组中的最大获益//更新最大获益profit = max(profit, prices[i]-buy);//更新最小值buy = min(prices[i],buy);}return profit;}};

121. 买卖股票的最佳时机_面试题63. 股票的最大利润_[找出数组中一个元素和它后面最大的元素的差值]

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。