【LeetCode】Best Time to Buy and Sell Stock 程序员炒股 part.1

来源:互联网 发布:2015云计算市场规模 编辑:程序博客网 时间:2024/06/06 01:55

【题目一】

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.

有这样一个数组,保存了每天的股票价格,找到最佳买点和卖点,输出最大盈利。

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/


【解析】

遍历数组找到最大值和最小值,输出两者只差。

值得注意的是,当最大值出现在最小值前,则会出错,因为我们这是股票买卖,手上有票才能卖。


因此,思路优化一下。

按顺序遍历一遍数组,每此都保存一个当前最小值,和当前最大盈利,用当前值与当前最小值做差,将其与当前最大盈利比较,较大者赋给当前最大盈利。

最后输出最大盈利。


此题简单,直接上程序:

class Solution {public:    int maxProfit(vector<int>& prices) {        int min_price = INT_MAX;        int max_profit = 0;        for(int i = 0 ; i < prices.size(); i++)        {            min_price = min(min_price, prices[i]);            max_profit = max(prices[i] - min_price, max_profit);        }        return max_profit;    }};

【题目二】

Say you have an array for which the ith element is the price of a given stock on day i.Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

与题一类似,只是可以进行多次买卖(同一天不能即买又卖)。

【解析】

原先思路是按照第一题先遍历一遍,找到最大盈利之后,接着后面的数字进行下一次遍历。

正确的思路是只要当前数值比后面的数值小,就做差,将差值累和,最后输出。

原先的思路还是复杂了,虽然正确的思路有点不讲道理,但却是没能想到。

程序如下:

class Solution {public:    int maxProfit(vector<int>& prices) {        int sum_profit = 0;        if(prices.size() == 0)            return 0;        for(int i = 0; i < prices.size()-1; i++)            if(prices[i+1] > prices[i])                sum_profit += prices[i+1] - prices[i];        return sum_profit;    }};


0 0
原创粉丝点击