[LeetCode]121. Best Time to Buy and Sell Stock(求近期股票能获得的最大利润)

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.

题目大意:
有一个数组,第i个元素是第i天给定股票的价格。
如果只允许最多完成一个交易(即购买一个交易并且卖出一个股票),则设计一个算法来找到最大利润。

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)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

思路1:

  • 解决这个问题的逻辑与使用Kadane算法的“最大子阵列问题”相同。
  • 价格数组为{1,7,4,11},利润数组则为{0 , 6 , -3 , 7}
  • 计算原始数组的差值(maxPro+ = price [i] - price [i-1]),并找到一个连续的子阵列给出最大的利润。 如果差值低于0,请将其重置为零。
  • 参考链接
  • 点击查看Kadane算法的“最大子阵列问题”

代码如下:

#include <iostream>
#include <vector>

using namespace std;
class Solution {
public:
    int maxProfit(vector<int>& prices) {//9ms
        int maxPro=0,res=0;
        for(int i=1; i<prices.size(); i++){
            maxPro += prices[i] - prices[i-1];
            maxPro = getMax(0, maxPro);
            res = getMax(res, maxPro);
            //cout << "res is = " << res << endl;
        }
        return res;
    }
    int getMax(int a, int b){return a>b ? a : b;}

};
int main()
{
    Solution s;
    vector<int> prices = {7, 1, 5, 3, 6, 4};
    cout << "max Profit is = " << s.maxProfit(prices) << endl;
    return 0;
}

思路2:

  • 遍历数组,每次遍历时,找出该价格之前的最小价格,同时计算当前最小价格后的日期的能得到最大利润
  • minPrice是从第0天到第i天的最低价格。 maxPro是从第0天到第i天可以获得的最大利润。
  • 在当前maxPro和prices[i] - minPrice之间获得较大的一个就是maxPro。
  • 参考链接

代码如下:

int maxProfit(vector<int> &prices) {//9ms
        int maxPro = 0;
        int minPrice = INT_MAX;
        for(int i = 0; i < prices.size(); i++){
            minPrice = min(minPrice, prices[i]);
            maxPro = max(maxPro, prices[i] - minPrice);
        }
        return maxPro;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值