Leetcode#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 (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)

题意

告诉你,有一个数组,数组中的第i个元素代表第i天的股票的价格,现在要求你只能进行一次买卖的交易且必须先买后卖,求出所给数组中买卖交易获得的最大的利润。

题解

普通的解法:找出数组中b-a的最大值(a在前为买,b在后为卖),枚举法双层循环

python语言
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max =-1
        for buy in range(0, len(prices)):
            for sell in range(buy+1, len(prices)):
                if prices[sell]-prices[buy]>max:
                    max = prices[sell] - prices[buy]
        if max<0:
            return 0
        else:
            return max

超时。。。。。。。。。。。。肿么办?
优化,找出相对最小值,用当前的值-相对最小值与利润相比较,取最大。

python语言
#python语言
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices)==0:
            return 0
        min_buy = prices[0]
        profit = -1
        for index in range(0, len(prices)):
            if min_buy > prices[index]:
                min_buy = prices[index]
            else:
                if prices[index]-min_buy>profit:
                    profit = prices[index]-min_buy
        return profit
C++语言
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size()==0)
            return 0;
        int min_buy=prices[0];
        int profit=-1;
        for(int i=0; i<prices.size(); i++)
        {
            if(min_buy > prices[i])
                min_buy = prices[i];
            else
            {
                if(prices[i] - min_buy > profit)
                    profit = prices[i] - min_buy;
            }
        }
        return profit;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值