给定一个数组prices,它的第i个元素prices[i]表示一支给定股票第i天的价格。 你只能选择某一天买入这只股票,并选择在未来的某一个不同的日子卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回0。
代码参考: 1classSolution {2public:3//dp[i][k][p]: the most profit for i days, k times transaction, now have p position.4//i: day i5//k: k-th transaction6//p: position:0(pre-act is sell) or 1(pre-act is buy)7//case_1: p=0 (act is sell):dp[i][k][0]= max:8/...
由上述分析可得如下代码: 1publicclassSolution {2publicintmaxProfit(int[] prices) {3if(prices.length == 0)4return0;56intprofit = 0, buyPrice = prices[0];78for(inti = 1; i < prices.length; i++){9if(prices[i] < prices[i - 1]){10profit += prices[i - 1] -buyPrice;11buyPrice...
用f[i][0]来记录,而f[i]就代表在第i天获得的最大收益是多少。 第二种情况:第i天买了股票,处于冷冻期(无法买入),用f[i][1] 来记录 第三种情况:没有持有股2票,也没有冷冻期(就是可以买入的状态)。用f[i][2]来表示。 我觉得作者这种思路跟我一开始想的没太大区别,只不过我是想f[i][0]可以买...
121.Best Time to Buy and Sell Stock 给定价格曲线,进行单次买进卖出,获取最大利润。 思路一: 不断更新买入点(局部最小值),不断更新最大利润(在当前价格卖出,若获取的利润为新高则更新最大利润),直到结束。 代码: classSolution{public:intmaxProfit(vector<int>&prices){inti=0;intmax_p=0;intmin_p=IN...
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 给定一个数组prices,其中prices[i]表示第i...
用两个指针,buy表示第几天买入,sell表示第几天卖出开始buy,sell都指向0,表示不操作36729^b^ssell后移表示这天卖出,计算收益是6-3=336729^^bssell后移表示这天卖出,计算收益是7-3=436729^^bssell后移表示这天卖出,计算收益是2-3=-13672912^^bs此外,如上图,当前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). ...
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. class Solution { public: //只做一次交易 寻找最大的差值即可 int maxProfit(vector<int>& prices) { ...
Trade stocks by speculating on the price action of listed companies or baskets of stocks. Explore stock trading and investing, as well as how to look for opportunities.