解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。 示例2: 输入: [1,2,3,4,5] 输出: 4 解...
题目信息 You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell ...
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). ...
同样不需要额外的空间,而且只需要O(n)的空间复杂度。思路就是我一开始没有钱,buy1是我第一次买股票之后剩的钱(肯定是负的,我白手起家,借钱买股票啊),sell1是我卖完第一次买的股票之后剩的钱(>=0),buy2是我用上回挣得钱(有可能需要找别人再借一点)买第二次股票,sell2是我卖完第二次股票之后剩下的钱。
1. BestTimetoBuyandSellStock 1 给出一个数组,代表第 i 天股票的价格。只能买卖一次,现在设计一个算法, 可以求出最大的profit。 用例:[7,1,5,3,6,4] ==> 5 [5,4,3,2,1] ==> 0 分析与思路 这个没啥好分析的,就是遍历一遍,以O(n)的时间复杂度,记录下买入价格。然后比较得出最大的 profit。
这道跟之前那道Best Time to Buy and Sell Stock 买卖股票的最佳时间很类似,但都比较容易解答。这道题由于可以无限次买入和卖出。我们都知道炒股想挣钱当然是低价买入高价抛出,那么这里我们只需要从第二天开始,如果当前价格比之前价格高,则把差值加入利润中,因为我们可以昨天买入,今日卖出,若明日价更高的话,还可以...
if (buy < prices[i]) profit += prices[i] - buy; buy = prices[i]; } return profit; } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Best Time to Buy and Sell Stock III 仅仅能操作两次时: 两次操作不能重叠。能够分成两部分:0...i的最大利润fst 和i...n-1的最大利润snd ...
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/ 题目tag:Array,Greedy 此题中,由于可以无限次进行交易,我们只需找出所有能赚钱的交易即可。 naive example 如图所示的例子中,总共有5天的价格,我们只需找出红色的两段,并将利润相加,即是我们要的答案。换言之,找出所有...
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). ...
Given an example[2,1,2,0,1], return 2 LeetCode上的原题,请参见我之前的博客Best Time to Buy and Sell Stock II。 classSolution {public:/** * @param prices: Given an integer array * @return: Maximum profit*/intmaxProfit(vector<int> &prices) {intres =0, n =prices.size();for(inti...