We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent bd68fd6 commit 62952cbCopy full SHA for 62952cb
best-time-to-buy-and-sell-stock/njngwn.java
@@ -0,0 +1,16 @@
1
+// Time Complexity: O(n), n: prices.length
2
+// Space Complexity: O(1), because 3 int-variables are declared -> O(1)+O(1)+O(1)
3
+class Solution {
4
+ public int maxProfit(int[] prices) {
5
+ int buyPrice = prices[0];
6
+ int sellPrice = 0;
7
+ int profit = 0; // store maxProfit
8
+
9
+ for (int i = 1; i < prices.length; ++i) {
10
+ buyPrice = Math.min(buyPrice, prices[i]);
11
+ profit = Math.max(profit, prices[i] - buyPrice);
12
+ }
13
14
+ return profit;
15
16
+}
0 commit comments