A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 121. Best Time to Buy and Sell Stock, the solution in this repository is mainly a greedy solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: greedy.
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are maxProfit.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01/**
02Say you have an array for which the ith element is the price of a given stock on day i.
03
04If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
05
06Note that you cannot sell a stock before you buy one.
07
08Example 1:
09
10Input: [7,1,5,3,6,4]
11Output: 5
12Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
13 Not 7-1 = 6, as selling price needs to be larger than buying price.
14Example 2:
15
16Input: [7,6,4,3,1]
17Output: 0
18Explanation: In this case, no transaction is done, i.e. max profit = 0.
19**/
20
21//Runtime: 8 ms, faster than 99.32% of C++ online submissions for Best Time to Buy and Sell Stock.
22//Memory Usage: 9.4 MB, less than 94.64% of C++ online submissions for Best Time to Buy and Sell Stock.
23
24class Solution {
25public:
26 int maxProfit(vector<int>& prices) {
27 if(prices.size() == 0) return 0;
28
29 int ans = 0;
30
31 int start = prices[0], end = prices[0];
32
33 for(int i = 0; i < prices.size(); i++){
34 if(prices[i] < start){
35 //restart as session
36 ans = max(ans, end - start);
37 start = prices[i];
38 end = prices[i];
39 }else{
40 //continue current session
41 end = max(end, prices[i]);
42 }
43 }
44 ans = max(ans, end - start);
45 return ans;
46 }
47};
48
49/**
50Approach 2: One Pass
51Algorithm
52
53Say the given array is:
54
55[7, 1, 5, 3, 6, 4]
56
57If we plot the numbers of the given array on a graph, we get:
58
59The points of interest are the peaks and valleys in the given graph. We need to find the largest peak following the smallest valley. We can maintain two variables - minprice and maxprofit corresponding to the smallest valley and maximum profit (maximum difference between selling price and minprice) obtained so far respectively.
60**/
61
62/**
63Time complexity : O(n). Only a single pass is needed.
64Space complexity : O(1). Only two variables are used.
65**/
66
67
68class Solution {
69public:
70 int maxProfit(vector<int>& prices) {
71 int valley = INT_MAX;
72 int ans = 0;
73 for(int i = 0; i < prices.size(); i++){
74 if(prices[i] < valley){
75 valley = prices[i];
76 }else if(prices[i] - valley > ans){
77 ans = prices[i] - valley;
78 }
79 }
80 return ans;
81 }
82};
83
84//Greedy
85//Runtime: 4 ms, faster than 97.14% of C++ online submissions for Best Time to Buy and Sell Stock.
86//Memory Usage: 7.5 MB, less than 100.00% of C++ online submissions for Best Time to Buy and Sell Stock.
87class Solution {
88public:
89 int maxProfit(vector<int>& prices) {
90 int n = prices.size();
91
92 int maxToTail = 0;
93 int profit, maxProfit = 0;
94
95 for(int i = n-1; i >= 0; i--){
96 maxToTail = max(maxToTail, prices[i]);
97 profit = max(maxToTail - prices[i], 0);
98 maxProfit = max(maxProfit, profit);
99 }
100
101 return maxProfit;
102 }
103};
104
105//Greedy
106//Runtime: 8 ms, faster than 49.52% of C++ online submissions for Best Time to Buy and Sell Stock.
107//Memory Usage: 13 MB, less than 5.51% of C++ online submissions for Best Time to Buy and Sell Stock.
108class Solution {
109public:
110 int maxProfit(vector<int>& prices) {
111 int ans = 0;
112 int buy = INT_MAX;
113 int cash = 0;
114
115 for(int price : prices){
116 /*
117 meaningless for first iteration,
118 in which buy is not set
119 */
120 cash = max(cash, price-buy);
121 buy = min(buy, price);
122 ans = max(ans, cash);
123 }
124
125 return ans;
126 }
127};
Cost