LeetCode解题报告
  • LeetCode解题报告
  • Easy
    • 1086. High Five
    • 283. Move Zeros
    • 443. String Compression
    • 38. Count and Say
    • 169. Majority Element
    • 349. Intersection of Two Arrays
    • 58. Length of Last Word
    • 70. Climbing Stairs
    • 455. Assign Cookies
    • 83. Remove Duplicates from Sorted List
    • 160. Intersection of Two Linked Lists
    • 206. Reverse Linked List
    • 122. Best Time to Buy and Sell Stock II
    • 760. Find Anagram Mappings
    • 804. Unique Morse Code Words
    • 905. Sort Array By Parity
    • 852. Peak Index in a Mountain Array
    • 961. N-Repeated Element in Size 2N Array
    • 832. Flipping an Image
    • 617. Merge Two Binary Trees
    • 700. Search in a Binary Search Tree
    • 409. Longest Palindrome
    • 657. Robot Return to Origin
    • 942. DI String Match
    • 728. Self Dividing Numbers
    • 944. Delete Columns to Make Sorted
    • 509. Fibonacci Number
    • 1021. Remove Outermost Parentheses
    • 171. Excel Sheet Column Number
    • 999. Available Captures for Rook
    • 252. Meeting Rooms
    • 482. License Key Formatting
    • 844. Backspace String Compare
    • 938. Range Sum of BST
    • 557. Reverse Words in a String III
    • 922. Sort Array By Parity II
    • 559. Maximum Depth of N-ary Tree
    • 849. Maximize Distance to Closest Person
    • 463. Island Perimeter
    • 665. Non-decreasing Array
    • 53. Maximum Subarray
    • 448. Find All Numbers Disappeared in an Array
    • 141. Linked List Cycle
    • 937. Reorder Log Files
    • 303. Range Sum Query - Immutable
    • 1103. Distribute Candies to People
    • 202. Happy Number
    • 232. Implement Queue using Stacks
    • 1119. Remove Vowels from a String
    • 9. Palindrome Number
    • 266. Palindrome Permutation
    • 125. Valid Palindrome
    • 246. Strobogrammatic Number
    • 168. Excel Sheet Column Title
    • 38. Count and Say
    • 242. Valid Anagram
    • 290. Word Pattern
    • 293. Flip Game
    • 205. Isomorphic Strings
    • 345. Reverse Vowels of a String
    • 344. Reverse String
    • 383. Ransom Note
    • 387. First Unique Character in a String
    • 58. Length of Last Word
    • 14. Longest Common Prefix
    • 1122. Relative Sort Array
    • 219. Contains Duplicate II
    • 13. Roman to Integer
    • 169. Majority Element
    • 299. Bulls and Cows
    • 290. Word Pattern
    • 205. Isomorphic Strings
    • 744. Find Smallest Letter Greater Than Target
    • 763. Partition Labels
    • 110. Balanced Binary Tree
    • 543. Diameter of Binary Tree
    • 111. Minimum Depth of Binary Tree
    • 392. Is Subsequence
    • 20. Valid Parentheses
    • 7. Reverse Integer
    • 66. Plus One
    • 258. Add Digits
    • 67. Add Binary
    • 367. Valid Perfect Square
    • 204. Count Primes
    • 941. Valid Mountain Array
    • 100. Same Tree
    • 101. Symmetric Tree
    • 226. Invert Binary Tree
    • 257. Binary Tree Paths
    • 112. Path Sum
    • 113. Path Sum II
    • 104. Maximum Depth of Binary Tree
    • 111. Minimum Depth of Binary Tree
    • 110. Balanced Binary Tree
    • 107. Binary Tree Level Order Traversal II
    • 235. Lowest Common Ancestor of a Binary Search Tree
    • 256. Paint House
    • 1165. Single-Row Keyboard
    • 637. Average of Levels in Binary Tree
    • 141. Linked List Cycle
    • 276. Paint Fence
    • 237. Delete Node in a Linked List
    • 203. Remove Linked List Elements
    • 21. Merge Two Sorted Lists
    • 278. First Bad Version
    • 35. Search Insert Position
    • 349. Intersection of Two Arrays
    • 350. Intersection of Two Arrays II
    • 234. Palindrome Linked List
    • 937. Reorder Data in Log Files
    • 733. Flood Fill
    • 1114. Print in Order
    • 27. Remove Element
    • 339. Nested List Weight Sum
    • 155. Min Stack
    • 225. Implement Stack using Queues
    • 389. Find the Difference
    • 136. Single Number
    • 26. Remove Duplicates from Sorted Array
    • 80. Remove Duplicates from Sorted Array II
    • 189. Rotate Array
    • 572. Subtree of Another Tree
    • 359. Logger Rate Limiter
    • 346. Moving Average from Data Stream
    • 118. Pascal's Triangle
    • 119. Pascal's Triangle II
    • 217. Contains Duplicate
    • 243. Shortest Word Distance
    • 121. Best Time to Buy and Sell Stock
  • Medium
    • 621. Task Scheduler
    • 1823. Find the Winner of the Circular Game
    • 340. Longest Substring with At Most K Distinct Characters
    • 209. Minimum Size Subarray Sum
    • 142. Linked List Cycle II
    • 451. Sort Characters By Frequency
    • 503. Next Greater Element II
    • 807. Max Increase to Keep City Skyline
    • 285. Inorder Successor in BST
    • 395. Longest Substring with At Least K Repeating Characters
    • 12. Integer to Roman
    • 807. Max Increase to Keep City Skyline
    • 392. Is Subsequence
    • 763. Partition Labels
    • 1110. Delete Nodes And Return Forest
    • 1109. Corporate Flight Bookings
    • 370. Range Addition
    • 238. Product of Array Except Self
    • 3. Longest Substring Without Repeating Characters
    • 161. One Edit Distance
    • 249. Group Shifted Strings
    • 49. Group Anagrams
    • 6. ZigZag Conversion
    • 294. Flip Game II
    • 345. Reverse Vowels of a String
    • 151. Reverse Words in a String
    • 324. Wiggle Sort II
    • 215. Kth Largest Element in an Array
    • 280. Wiggle Sort
    • 56. Merge Intervals
    • 287. Find the Duplicate Number
    • 11. Container With Most Water
    • 271. Encode and Decode Strings
    • 5. Longest Palindromic Substring
    • 39. Combination Sum
    • 229. Majority Element II
    • 275. H-Index II
    • 244. Shortest Word Distance II
    • 55. Jump Game
    • 245. Shortest Word Distance III
    • 40. Combination Sum II
    • 216. Combination Sum III
    • 77. Combinations
    • 78. Subsets
    • 90. Subsets II
    • 131. Palindrome Partitioning
    • 17. Letter Combinations of a Phone Number
    • 739. Daily Temperatures
    • 46. Permutations
    • 49. Group Anagrams
    • 253. Meeting Rooms II
    • 540. Single Element in a Sorted Array
    • 267. Palindrome Permutation II
    • 187. Repeated DNA Sequences
    • 165. Compare Version Numbers
    • 43. Multiply Strings
    • 144. Binary Tree Preorder Traversal
    • 94. Binary Tree Inorder Traversal
    • 102. Binary Tree Level Order Traversal
    • 129. Sum Root to Leaf Numbers
    • 298. Binary Tree Longest Consecutive Sequence
    • 337. House Robber III
    • 103. Binary Tree Zigzag Level Order Traversal
    • 199. Binary Tree Right Side View
    • 1169. Invalid Transactions
    • 98. Validate Binary Search Tree
    • 236. Lowest Common Ancestor of a Binary Tree
    • 254. Factor Combinations
    • 47. Permutations II
    • 31. Next Permutation
    • 60. Permutation Sequence
    • 62. Unique Paths
    • 63. Unique Paths II
    • 279. Perfect Squares
    • 139. Word Break
    • 322. Coin Change
    • 64. Minimum Path Sum
    • 221. Maximal Square
    • 24. Swap Nodes in Pairs
    • 328. Odd Even Linked List
    • 92. Reverse Linked List II
    • 120. Triangle
    • 82. Remove Duplicates from Sorted List II
    • 2. Add Two Numbers
    • 33. Search in Rotated Sorted Array
    • 81. Search in Rotated Sorted Array II
    • 153. Find Minimum in Rotated Sorted Array
    • 162. Find Peak Element
    • 374. Guess Number Higher or Lower
    • 34. Find First and Last Position of Element in Sorted Array
    • 300. Longest Increasing Subsequence
    • 48. Rotate Image
    • 54. Spiral Matrix
    • 59. Spiral Matrix II
    • 73. Set Matrix Zeroes
    • 311. Sparse Matrix Multiplication
    • 74. Search a 2D Matrix
    • 240. Search a 2D Matrix II
    • 370. Range Addition
    • 79. Word Search
    • 200. Number of Islands
    • 994. Rotting Oranges
    • 286. Walls and Gates
    • 323. Number of Connected Components in an Undirected Graph
    • 130. Surrounded Regions
    • 60. Permutation Sequence
    • 127. Word Ladder
    • 79. Word Search
    • 364. Nested List Weight Sum II
    • 150. Evaluate Reverse Polish Notation
    • 394. Decode String
    • 347. Top K Frequent Elements
    • 332. Reconstruct Itinerary
    • 341. Flatten Nested List Iterator
    • 318. Maximum Product of Word Lengths
    • 207. Course Schedule
    • 210. Course Schedule II
    • 384. Shuffle an Array
    • 277. Find the Celebrity
    • 133. Clone Graph
    • 399. Evaluate Division
    • 356. Line Reflection
    • 310. Minimum Height Trees
    • 223. Rectangle Area
    • 261. Graph Valid Tree
    • 211. Add and Search Word - Data structure design
    • 208. Implement Trie (Prefix Tree)
    • 362. Design Hit Counter
    • 281. Zigzag Iterator
    • 8. String to Integer (atoi)
    • 15. 3Sum
    • 18. 4Sum
    • 134. Gas Station
    • 981. Time Based Key-Value Store
    • 1007. Minimum Domino Rotations For Equal Row
    • 1057. Campus Bikes
    • 309. Best Time to Buy and Sell Stock with Cooldown
  • Hard
    • 4. Median of Two Sorted Arrays
    • 188. Best Time to Buy and Sell Stock IV
    • 123. Best Time to Buy and Sell Stock III
    • 145. Binary Tree Postorder Traversal
    • 265. Paint House II
    • 154. Find Minimum in Rotated Sorted Array II
    • 315. Count of Smaller Numbers After Self
    • 305. Number of Islands II
    • 42. Trapping Rain Water
    • 45. Jump Game II
Powered by GitBook
On this page

Was this helpful?

  1. Hard

123. Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

解题要点:

鉴于本题只有两个交易,按照顺序进行买卖,然后记录最大profit。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        one = sys.maxint
        two = sys.maxint
        profit1 = profit2 = 0
        for i in range(len(prices)):
            one = min(one, prices[i])
            profit1 = max(profit1, prices[i] - one)
            two = min(two, prices[i] - profit1)
            profit2 = max(profit2, prices[i] - two)
        return profit2
Previous188. Best Time to Buy and Sell Stock IVNext145. Binary Tree Postorder Traversal

Last updated 5 years ago

Was this helpful?