File tree Expand file tree Collapse file tree 3 files changed +71
-0
lines changed Expand file tree Collapse file tree 3 files changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(1)
3
+
4
+ class Solution {
5
+ public:
6
+ int maxProfit (vector<int > &prices) {
7
+ const int n = prices.size ();
8
+
9
+ if (n < 2 )
10
+ return 0 ;
11
+
12
+ // Greedy Algorithm
13
+ int ans = 0 ;
14
+ for (int i = 1 , valley = prices[0 ]; i < n; ++i) {
15
+ ans = max (ans, prices[i] - valley);
16
+ valley = min (valley, prices[i]);
17
+ }
18
+
19
+ return ans;
20
+ }
21
+ };
Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(1)
3
+
4
+ class Solution {
5
+ public:
6
+ int maxProfit (vector<int > &prices) {
7
+ const int n = prices.size ();
8
+ int ans = 0 ;
9
+
10
+ for (int i = 1 ; i < n; ++i) {
11
+ int diff = prices[i] - prices[i - 1 ];
12
+ if (diff > 0 )
13
+ ans += diff;
14
+ }
15
+
16
+ return ans;
17
+ }
18
+ };
Original file line number Diff line number Diff line change
1
+ // Time Complexity: O(n)
2
+ // Space Complexity: O(n)
3
+
4
+ class Solution {
5
+ public:
6
+ int maxProfit (vector<int > &prices) {
7
+ const int n = prices.size ();
8
+
9
+ if (n < 2 )
10
+ return 0 ;
11
+
12
+ vector<int > f (n, 0 );
13
+ vector<int > g (n, 0 );
14
+
15
+ for (int i = 1 , valley = prices[0 ]; i < n; ++i) {
16
+ f[i] = max (f[i - 1 ], prices[i] - valley);
17
+ valley = min (valley, prices[i]);
18
+ }
19
+
20
+ for (int i = n - 2 , peak = prices[n - 1 ]; i >= 0 ; --i) {
21
+ g[i] = max (g[i + 1 ], peak - prices[i]);
22
+ peak = max (peak, prices[i]);
23
+ }
24
+
25
+ int ans = 0 ;
26
+ for (int i = 0 ; i < n; ++i) {
27
+ ans = max (ans, f[i] + g[i]);
28
+ }
29
+
30
+ return ans;
31
+ }
32
+ };
You can’t perform that action at this time.
0 commit comments