力扣122(java&python)-买卖股票的最佳时机 II(中等)

题目:

给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润 。

 示例 1:

输入:prices = [7,1,5,3,6,4]
输出:7
解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
  随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。
总利润为 4 + 3 = 7 。
示例 2:

输入:prices = [1,2,3,4,5]
输出:4
解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
  总利润为 4 。
示例 3:

输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 交易无法获得正利润,所以不参与交易可以获得最大利润,最大利润为 0 。
 

提示:

1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

一、贪心算法

参考@【Krahets】

贪心算法:在每一步都做出当时看起来的最佳选择,也就是总是做出局部最优的选择,寄希望这样的选择能导致全局最优解。

等价于"每天都买卖",遍历整个股票交易的列表价格,计算出第 i - 1 天买入,第 i 天卖出的利润 temp,即 temp = prices[i] - prices[i-1],如果计算出的利润为正值即temp > 0,则算入到总利润 profit 中,如果计算出的利润为负值或0,即temp <= 0,则直接跳过,最后返回总利润即可。

java代码:

 1 class Solution {
 2     public int maxProfit(int[] prices) {
 3         int profit = 0;
 4         for(int i = 1; i < prices.length; i++){
 5             int temp = prices[i] - prices[i - 1];
 6             if(temp > 0){
 7                 profit += temp;
 8             }
 9         }
10         return profit;
11     }
12 }

 python3代码:

 1 class Solution:
 2     def maxProfit(self, prices: List[int]) -> int:
 3         if len(prices) < 2:
 4             return 0
 5         profit = 0
 6         for i in range(1, len(prices)):
 7             temp = prices[i] - prices[i-1]
 8             if temp > 0:
 9                 profit += temp
10         return profit

 二、动态规划

参考@liweiwei1419

1.定义状态:dp[i][j]:表示到下标为 i 的这一天,持股状态为 j 时,手上拥有的利润数;

第一维 i :表示下标为 i 的那一天;

第二维 j :表示下标为 i 的那一天,手上拥有的是股票还是利润,0表示利润,1表示股票。

2.状态转移方程:状态从拥有利润开始,到结束也只是关心拥有的利润数。每一天的状态可以转移,也就可以不变。

3.确定初始值:

开始值时如果什么都没做拥有利润就为0:dp[0][0] = 0;

开始值时如果就买入股票,则当前拥有的利润数就是当天股价的相反数:dp[0][1] = -price[0];

4.输出值:最终是要输出利润:dp[n -1][0] 

java代码:

 1 class Solution {
 2     public int maxProfit(int[] prices) {
 3         int n = prices.length;
 4         if(n < 2) return 0;
 5         int[][] dp = new int[n][2];
 6 
 7         //定义初始值
 8         dp[0][0] = 0;
 9         dp[0][1] = -prices[0];
10 
11         //状态变化
12         for(int i = 1; i < n; i++){
13             //卖出股票,获得利润
14             dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
15             //买入股票,减少利润
16             dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]);
17         }
18         return dp[n-1][0];
19     }
20 }

posted on 2022-10-26 10:14  我不想一直当菜鸟  阅读(29)  评论(0编辑  收藏  举报