leetcode--Best Time to Buy and Sell Stock i ii iii

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.

题目链接:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

给一个数prices[],prices[i]代表股票在第i天的售价,求出只做一次交易(一次买入和卖出)能得到的最大收益。

只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o....i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。

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

        }
        return money;

    }
};
<h3 style="box-sizing: border-box; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-weight: 500; line-height: 1.1; color: rgb(51, 51, 51); margin-top: 20px; margin-bottom: 10px; font-size: 24px; display: inline;">Best Time to Buy and Sell Stock II</h3><span style="color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 20px;"> </span>
<span style="color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 20px;"></span><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Say you have an array for which the <span style="box-sizing: border-box;">i</span><span style="box-sizing: border-box; position: relative; font-size: 12px; line-height: 0; vertical-align: baseline; top: -0.5em;">th</span> element is the price of a given stock on day <span style="box-sizing: border-box;">i</span>.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">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).</p>

此题和上面一题的不同之处在于不限制交易次数。也是一次遍历即可,只要可以赚就做交易。题目链接:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

此题和上面一题的不同之处在于不限制交易次数。也是一次遍历即可,只要可以赚就做交易。

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

Best Time to Buy and Sell Stock III

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 at most two transactions.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

题意:获取股票最大收益,最多可交易两次,且必须完成一桩交易之后才能进行另一桩交易。当然,可以第i天卖出后又当天买回。

因为最多两次交易,很容易联想到将数组分为两部分,对两部分数组分别求最大值,然后将两个最大值相加,经多次比较,得到总的最大值。但是这会出现一个问题,时间复杂度太大。经测试,这种方式会导致Time Limited Exceed的错误。

那么现在需要考虑一下有没有可以改进的方法,答案是有的,可以利用一维的动态规划来做,因为我们可以观察到,之前的方案之所以复杂度太大是因为有很多重复的计算。而动态规划可以采取的方式是:

1)新开一个数组maxProfitWith,这个数组用来保存第i天可以获得的最大收益。

2)将prices数组都遍历一遍之后,可以知道最后一项,即maxProfitWith[size-1]即为遍历一遍时的最大收益。

3)我们再逆序遍历一遍,计算当前i到最后一天的最大收益,与之前的0至第i天的最大收益相加,可以得到总的最大收益finalProfit,比较之后,可以得到最终结果。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
    	if (prices.size()<=1)
	{
		return 0;
	}
    vector<int>max_profit_list;
	max_profit_list.push_back(0);
	int lowest=prices[0];
	int maxprofit=0;
	for (int i=1;i<prices.size();i++)
	{
		if (prices[i]-lowest>maxprofit)
		{
			maxprofit=prices[i]-lowest;
		}
		max_profit_list.push_back(maxprofit);
		if (prices[i]<lowest)
		{
			lowest=prices[i];
		}
	}
	int ret=max_profit_list[prices.size()-1];
	int highest=prices[prices.size()-1];
	maxprofit=0;
	for (int i=prices.size()-2;i>=0;i--)
	{
		if (highest-prices[i]>maxprofit)
		{
			maxprofit=highest-prices[i];
		}
		int total_profit=maxprofit+max_profit_list[i];
		if (ret<total_profit)
		{
			ret=total_profit;
		}
		if (prices[i]>highest)
		{
			highest=prices[i];
		}
	}
	return ret;
}
};
时间: 2024-10-13 12:21:46

leetcode--Best Time to Buy and Sell Stock i ii iii的相关文章

[Leetcode] Best Time to Buy and Sell Stock I,II,III,IV

三种股票交易算法 一.交易次数没有限制 使用贪心策略,找最长递增序列,同时累加相应利润. 二.只有一次交易 使用动态规划算法,从前往后,依次记记录相应时间节点前面的最小price,同时获得在这个节点的最大利润,同时更新最小price 三.最多两次 使用两次动态规划 1.从左向右,记录在相应的时间节点卖出的最大利润,实际上就是问题二 2.从右向左,记录在相应的时间节点买入的最大利润,因此这里需要记录最大的price. 将each 的left[index]+ right[index]曲最大值. 四.

【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告

Best Time to Buy and Sell Stock I 题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格. 如果只允许进行一次交易,也就是说只允许买一支股票并卖掉,求最大的收益. 分析:动态规划法.从前向后遍历数组,记录当前出现过的最低价格,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益,整个遍历过程中,出现过的最大收益就是所求. 代码:时间O(n),空间O(1). Best Time to Buy and Sell Stock II 题目:用一

[leetcode]_Best Time to Buy and Sell Stock I &amp;&amp; II

一个系列三道题,我都不会做,google之答案.过了两道,第三道看不懂,放置,稍后继续. 一.Best Time to Buy and Sell Stock I 题目:一个数组表示一支股票的价格变换.要求只买卖一次,获得最大收益. 思路:一开始我认为是寻找最大.最小值,但由于最大值不一定总是出现在最小值的后面,因此WA. 参考思路:DP.对第i个价格,减去前i-1个价格中的最小值(保证该收益是在第i个价格卖出的最大收益),其收益与之前获得的最大收益相比. 代码: 1 public int max

Best Time to Buy and Sell Stock I &amp;&amp; II &amp;&amp; III

题目1: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 algori

[Lintcode] Best Time to Buy and Sell Stock I, II, III &amp;&amp; Maximum Subarray

买卖股票系列 && Subarray 相关题目: Best Time to Buy and Sell Stock I && II && III (IV 单独开贴) Maximum Subarray I && II 为什么这些我要总结到一起呢?因为思路基本一致. 题目简略: 买卖股票1: 一次买卖,利润最大. 买卖股票2: N次买卖,利润最大. 买卖股票3: 2次不重叠的买卖,利润最大. Maximum Subarray: Given an a

LeetCode之“动态规划”:Best Time to Buy and Sell Stock I &amp;&amp; II &amp;&amp; III &amp;&amp; IV

1. Best Time to Buy and Sell Stock I 题目链接 题目要求: 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), desi

leetcode day6 -- String to Integer (atoi) &amp;&amp; Best Time to Buy and Sell Stock I II III

1.  String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is inte

[Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III

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

Best Time to Buy and Sell Stock I,II,III [leetcode]

Best Time to Buy and Sell Stock I 只能作一次操作时:维护preMin记录之前出现的最小值 代码如下: int maxProfit(vector<int> &prices) { if (prices.size() == 0) return 0; int profit = 0; int preMin = prices[0]; for (int i = 1; i < prices.size(); i++) { if (prices[i] < pr