【leetcode】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.


题解:简单的动态规划题。用prices存储每天的股票价格,dp[i]表示第i天的最大利润,minmum表示遍历到当前为止prices中最小的元素。

那么在第i+1天有两种选择:

1.在这一天卖掉股票,那么显然可以获得的最大利润是prices[i+1]-minmum;

2.在这一天之前就把股票卖掉,那么可以获得的最大利润即使前i天可以获得最大利润。

dp[i] = max({dp[0],dp[1],...,dp[i]},prices[i+1]-minmum)

其实上述的dp数组也不需要,只要一个profit变量记录到当前为止可以获得最大的利润就可以了。

代码如下:

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() == 0)
            return 0;

        int Profit = 0;
        int minmum_price = prices[0];

        for(int i= 1;i < prices.size();i++){
            if(prices[i] < minmum_price)
                minmum_price = prices[i];
            if(prices[i]-minmum_price > Profit)
                Profit = prices[i]-minmum_price;
        }

        return Profit;
    }
};

int main(){
    vector <int> prices;
    prices.push_back(3);
    prices.push_back(3);
    prices.push_back(5);
    prices.push_back(0);
    prices.push_back(0);
    prices.push_back(3);
    prices.push_back(1);
    prices.push_back(4);

    Solution s;
    cout <<s.maxProfit(prices)<<endl;
}

 JAVA版本代码:设置一个最小值记录当前为止最低的价格,一个answer变量记录当前为止可以获得最大收益,那么在每一步answer = max(answer,prices[i]-nowMin),最后的answer就是最大的收益。

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         int nowMin = Integer.MAX_VALUE;
 4         int answer = 0;
 5         for(int i = 0;i < prices.length;i++){
 6             nowMin = nowMin < prices[i]?nowMin:prices[i];
 7             answer = answer > prices[i]-nowMin?answer:prices[i]-nowMin;
 8         }
 9         return answer;
10     }
11 }

 

 

转载于:https://www.cnblogs.com/sunshineatnoon/p/3732428.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值