leetcode笔记:Best Time to Buy and Sell Stock

来源:互联网 发布:mac玩游戏卡 编辑:程序博客网 时间:2024/05/01 03:36

一. 题目描述

Say you have an array for which the i-th 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天的股价,只允许买入卖出一次,问怎么买卖使得收益最大?

首先想到的是把原始估价序列变成差分序列,则可转化为求数组的最大子段和。

或者,可以用类似动态规划的思想,假设在第i天买入,什么时候能赚到的最多的钱呢?不外乎就是在第i + 1n天中选择最大的股价减去第i天的股价。

三. 示例代码

// 第二种方法#include <iostream>#include <vector>using namespace std;class Solution {public:    int maxProfit(vector<int> &prices)     {        if (prices.size() == 0)            return 0;        int maxPrice = prices[prices.size() - 1];        int profit = 0;        for(size_t i = prices.size() - 1; i >= 0; i--)        {            maxPrice = max(maxPrice, prices[i]);            profit = max(profit, maxPrice - prices[i]);        }        return profit;    }};

四. 小结

与该题相关的题目还有好几道。后续更新…

3 0