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

71 篇文章 0 订阅
5 篇文章 0 订阅
给定一个数组,表示股票每日价格,设计一个算法在只能进行一次交易的情况下找到最大利润。不能在买入前卖出股票。算法思路包括暴力求解和动态规划。动态规划公式:新添加元素e时,最大收益=max(当前最大收益,e-之前数组的最小值)。
摘要由CSDN通过智能技术生成

描述

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 0
        
        buy = prices[0]
        profit = 0
        
        for 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;
        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值