File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } prices
3
+ * @return {number }
4
+ */
5
+
6
+ // TC : O(n)
7
+ // SC : O(1)
8
+
9
+ var maxProfit = function ( prices ) {
10
+ if ( prices . length === 1 ) {
11
+ return 0 ;
12
+ }
13
+
14
+ // Two variables (profitMax and priceMin) are used to store the maximum profit and minimum price seen, which require O(1) space.
15
+ let profitMax = 0 ;
16
+ let priceMin = prices [ 0 ] ;
17
+
18
+ for ( const price of prices ) {
19
+ const profit = price - priceMin ;
20
+ profitMax = Math . max ( profit , profitMax ) ;
21
+ priceMin = Math . min ( price , priceMin ) ;
22
+ }
23
+
24
+ return profitMax ;
25
+ } ;
26
+
27
+ // Why Constants Are Ignored in Big-O
28
+ // In Big-O notation, O(2) is simplified to O(1) because constants are irrelevant in asymptotic analysis.
29
+ // Big-O focuses on how resource usage scales with input size, not fixed values.
30
+
31
+ // Using 2 variables: O(1)
32
+ // Using 10 variables: O(1)
33
+ // Using 100 variables: O(1)
34
+
35
+ // What Space Complexity Looks Like for Larger Growth
36
+ // O(n): Memory grows linearly with the input size (e.g., storing an array of n elements).
37
+ // O(n^2): Memory grows quadratically (e.g., a 2D matrix with n*n elements).
38
+ // 𝑂(log 𝑛): Memory grows logarithmically (e.g., recursive calls in binary search).
39
+ // O(1): Fixed memory usage, regardless of input size (e.g., using a fixed number of variables).
40
+
41
+
You can’t perform that action at this time.
0 commit comments