Day 49 | 121. Best Time to Buy and Sell Stock I | 122. Best Time to Buy and Sell Stock II

该博客记录了LeetCode刷题过程,涵盖二分查找、链表操作、二叉树遍历等多种类型题目。重点讲解了121和122题“买卖股票的最佳时机”,分析了动态规划数组含义、递归公式、初始化及遍历顺序,对比了可买卖一次和多次的不同情况。

Day 1 | 704. Binary Search | 27. Remove Element | 35. Search Insert Position | 34. First and Last Position of Element in Sorted Array
Day 2 | 977. Squares of a Sorted Array | 209. Minimum Size Subarray Sum | 59. Spiral Matrix II
Day 3 | 203. Remove Linked List Elements | 707. Design Linked List | 206. Reverse Linked List
Day 4 | 24. Swap Nodes in Pairs| 19. Remove Nth Node From End of List| 160.Intersection of Two Lists
Day 6 | 242. Valid Anagram | 349. Intersection of Two Arrays | 202. Happy Numbe | 1. Two Sum
Day 7 | 454. 4Sum II | 383. Ransom Note | 15. 3Sum | 18. 4Sum
Day 8 | 344. Reverse String | 541. Reverse String II | 替换空格 | 151.Reverse Words in a String | 左旋转字符串
Day 9 | 28. Find the Index of the First Occurrence in a String | 459. Repeated Substring Pattern
Day 10 | 232. Implement Queue using Stacks | 225. Implement Stack using Queue
Day 11 | 20. Valid Parentheses | 1047. Remove All Adjacent Duplicates In String | 150. Evaluate RPN
Day 13 | 239. Sliding Window Maximum | 347. Top K Frequent Elements
Day 14 | 144.Binary Tree Preorder Traversal | 94.Binary Tree Inorder Traversal| 145.Binary Tree Postorder Traversal
Day 15 | 102. Binary Tree Level Order Traversal | 226. Invert Binary Tree | 101. Symmetric Tree
Day 16 | 104.MaximumDepth of BinaryTree| 111.MinimumDepth of BinaryTree| 222.CountComplete TreeNodes
Day 17 | 110. Balanced Binary Tree | 257. Binary Tree Paths | 404. Sum of Left Leaves
Day 18 | 513. Find Bottom Left Tree Value | 112. Path Sum | 105&106. Construct Binary Tree
Day 20 | 654. Maximum Binary Tree | 617. Merge Two Binary Trees | 700.Search in a Binary Search Tree
Day 21 | 530. Minimum Absolute Difference in BST | 501. Find Mode in Binary Search Tree | 236. Lowes
Day 22 | 235. Lowest Common Ancestor of a BST | 701. Insert into a BST | 450. Delete Node in a BST
Day 23 | 669. Trim a BST | 108. Convert Sorted Array to BST | 538. Convert BST to Greater Tree
Day 24 | 77. Combinations
Day 25 | 216. Combination Sum III | 17. Letter Combinations of a Phone Number
Day 27 | 39. Combination Sum | 40. Combination Sum II | 131. Palindrome Partitioning
Day 28 | 93. Restore IP Addresses | 78. Subsets | 90. Subsets II
Day 29 | 491. Non-decreasing Subsequences | 46. Permutations | 47. Permutations II
Day 30 | 332. Reconstruct Itinerary | 51. N-Queens | 37. Sudoku Solver
Day 31 | 455. Assign Cookies | 376. Wiggle Subsequence | 53. Maximum Subarray
Day 32 | 122. Best Time to Buy and Sell Stock II | 55. Jump Game | 45. Jump Game II
Day 34 | 1005. Maximize Sum Of Array After K Negations | 134. Gas Station | 135. Candy
Day 35 | 860. Lemonade Change | 406. Queue Reconstruction by Height | 452. Minimum Number of Arrows
Day 36 | 435. Non-overlapping Intervals | 763. Partition Labels | 56. Merge Intervals
Day 37 | 738. Monotone Increasing Digits | 714. Best Time to Buy and Sell Stock | 968. BT Camera
Day 38 | 509. Fibonacci Number | 70. Climbing Stairs | 746. Min Cost Climbing Stairs
Day 39 | 62. Unique Paths | 63. Unique Paths II
Day 41 | 343. Integer Break | 96. Unique Binary Search Trees
Day 42 | 0-1 Backpack Basic Theory(一)| 0-1 Backpack Basic Theory(二)| 416. Partition Equal Subset Sum
Day 43 | 1049. Last Stone Weight II | 494. Target Sum | 474. Ones and Zeroes
Day 44 | Full Backpack Basic Theory | 518. Coin Change II | 377. Combination Sum IV
Day 45 | 70. Climbing Stairs | 322. Coin Change | 279. Perfect Squares
Day 46 | 139. Word Break | Backpack Question Summary
Day 48 | 198. House Robber | 213. House Robber II | 337. House Robber III


121. Best Time to Buy and Sell Stock

Question Link

class Solution {
    public int maxProfit(int[] prices) {
        int[][] dp = new int[prices.length][2];
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for(int i = 1; i < prices.length; i++){
            dp[i][0] = Math.max(dp[i-1][0], -prices[i]);
            dp[i][1] = Math.max(dp[i-1][1], prices[i] + dp[i-1][0]);
        }
        return dp[prices.length-1][1];
    }
}
  • Meaning of dp array
    • dp[i][0]: maximum cash of holding stocks on day i
    • dp[i][1]: maximum cash of doesn’t holding stocks on day i
    • The hold here doesn’t mean buy today. It is also possible that I bought it yesterday and keep it today.
  • Recursion Formula:
    • If hold the stock on i-1 day, let’s keep it that way.
    • If buy stock on day i, current cash is -prices[i]
    • So the dp[i][0] should choose the larger one: dp[i][0] = max(dp[i - 1][0], -prices[i])
    • If doesn’t hold the the stock on i - 1, let’s keep it that way.
    • If sell stock on day i, current cash is prices[i] + dp[i - 1][0]
    • Again dp[i][1] takes the larger one: dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])
  • Initialize the DP array
    • According to the recursion formula, the values of dp array are derived from dp[0][0] and dp[0][1]
    • dp[0][0] = -prices[0]: buy the stock on day 0, so the profit is -prices[0]
    • dp[0][1] = 0: doesn’t hold stock on day 0,so the profit is 0
  • Traversal Order is from front to back.

122. Best Time to Buy and Sell Stock II

Question Link

class Solution {
    public int maxProfit(int[] prices) {
        int[][] dp = new int[prices.length][2];
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        for(int i = 1; i < prices.length; i++){
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] - prices[i]);
            dp[i][1] = Math.max(dp[i-1][1], prices[i] + dp[i-1][0]);
        }
        return dp[prices.length - 1][1];
    }
}
  • The only difference between this with 121. Best Time to Buy and Sell Stock is the derivation of dp[i][0] when bought the stock on day i
    • In 121. Best Time to Buy and Sell Stock, because you can only buy and sell stocks once. So If you buy the stock on day i, the dp[i][0] = -prices[i]
    • In this question, cause you can buy and sell stocks multiple times. The cash held should include the profits from the previous trading.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值