You are given an array prices where prices[i] is the price of a given stock on the ith day.
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.
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
1 <= prices.length <= 105 0 <= prices[i] <= 104
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
- idea1:首先想到的就是暴力解法,两重遍历取差值最大
- idea2:题目说有一天买入,再找另外一天卖出,我们可以假设第i天卖出,那么只要知道i-1天的最小值,就知道第i天卖出去的收入,这样边遍历,边更新最大值就可以了。
- idea3:利用动态规划,dp[i]表示前i天(包括i)的最小值,这样边遍历,边计算当天的收入,一边更新最大值就可以了。
我想到的是这个思路,原以为这个思路也是动态规划,但是好像写下来也不是,就是普通思路。我的代码如下,已经成功。
public static int maxProfit(int[] prices) { int n = prices.length; int min = prices[0]; int max = 0; // i范围[1,n] int[] dp = new int[n + 1]; // 前i-1天(包括i-1)买入,第i天卖出获得的收入 for (int i = 2; i < n + 1; i++) { if (min > prices[i - 2]) { min = prices[i - 2]; } dp[i] = prices[i - 1] - min; if (max < dp[i]) { max = dp[i]; } } System.out.println(Arrays.toString(dp)); return max; }
我这里是完全严格按照题目的意思,计算的前i-1天的最小值,和力扣答案里面包含当天当卖的情况不一样。
1-4:idea3代码public static int maxProfit2(int[] prices) { int n = prices.length; int max = 0; // i范围[1,n] int[] dp = new int[n + 1]; // 前i天(包括i)天的历史最低值 dp[1] = prices[0]; for (int i = 2; i < n + 1; i++) { dp[i] = Math.min(dp[i - 1], prices[i - 1]); int cur = prices[i - 1] - dp[i]; max = Math.max(cur, max); } System.out.println(Arrays.toString(dp)); return max; } // 滚动数组的情况 public static int maxProfit3(int[] prices) { int n = prices.length; int max = 0; // i范围[1,n] int min = prices[0]; for (int i = 2; i < n + 1; i++) { min = Math.min(min, prices[i - 1]); int cur = prices[i - 1] - min; max = Math.max(cur, max); } return max; }
用的是动态规划的思想,但是很明显他算上了当天购入当天卖的情况,虽然不影响最后的结果,因为当天买,当天卖利润是0,只要结果里面有比0大的情况,这个就会被覆盖。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)