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.
    翻译:
    假设你有一个数组,其中第i个元素是第i天给定股票的价格。
    如果你只被允许完成最多一个交易(即,买一个,卖一股股票),设计一个算法来找到最大利润。
    例子:
    (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)
    (2)Input: [7, 6, 4, 3, 1]
    Output: 0
    In this case, no transaction is done, i.e. max profit = 0.
  • 解题思路
    这个题目主要是想找到股价差距最大的两天,把他们的差值求出来,作为最大收益。
    写一个函数int maxProfit(vector& prices),返回最大收益。
    (1)若股票数组数量小于2,要么是0要么是1,则没有股票交易的发生,返回0。
    (2)若股票数组数量大于等于2,则有可能发生股票交易。下面讨论这种情况。
    (3)定义三个变量,res记录结果,r和l,期中r表示数组右边的值(ie,天数靠后的股票),l表示数组左边的值(ie,天数靠前的股票),那么,如何通过这三个变量来求得股票交易的最大收益呢?
    (4)开一个循环,循环里面先对res赋值为当前的res和prices[r]-prices[l],也就是说,每次循环将会不断更新res的值,到最后将会找到最大的res。因为我们将会对r和l进行操作。
    (5)紧接着在循环里面,我们对r和l进行操作,主要是,检测到prices[r]小于prices[l] , 即后面的时间有比当前时间股价还小的时间,则将l移动到那个时间(r和l其实对应的是时间),操作很简单,直接l=r
    举个栗子:
    Input: [7, 1, 5, 3, 6, 4]
    一开始res=0,l=0,r=1
    很明显,当l=1,r=2时,res才有了大于0的结果,为5-1=4
    然后r更新为3,发现股票3-1=2,更新res的结果仍为4
    r更新为4,此时更新股票为6-1=5!出现了新的最大值
    然后就没有然后了。
    返回maxProfit=5。
    结果讨论:如果是问题描述中的例子二,由于是一个递减的数组,res将会一直是0;其实本算法的核心就是 一直让r设置为数组中的小值,然后判断prices[r]和prices[l]来更新res和l,使得一直有大数减小数来取得最大收益。当然如果前面已经出现了maxProfit,再更新l,也取不到更大的值了。
  • 完整代码
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

int maxProfit(vector<int>& prices)
{
    if (prices.size() < 2)
        return 0;
    int res=0;
    int l = 0,r = 1;
    while (r < prices.size())
    {
        res = max(res, prices[r] - prices[l]);//更新res为此前的res和新的(prices[r]-prices[l])差值
        if (prices[r] < prices[l])//如果发现一个比prices[l]更小的值prices[r],则更新l为r。
            l = r;
        r++;
    }
    return res;
}
int main()
{
    int a[6] = { 7,6,4,3,1,0};
    vector<int> v(a, a + 6);
    printf("The array is:\n");
    for (int i = 0; i < v.size(); i++)
        cout << v[i] << ' ';
    cout << "Max profit is:\n";
    cout << maxProfit(v);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值