-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBest Time to Buy and Sell Stock.java
105 lines (79 loc) · 3.15 KB
/
Best Time to Buy and Sell Stock.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
class Solution {
public int mySolution(int[] prices) {
/*
* SIDE NOTE: This is the solution that I came up with :)
* IMPORTANT: It really helps to create a graph and understand it from a non-programming perspective.
* Do what you normally do when trading stocks, buy low and sell high :)
*
* Time Complexity: O(n) where n = length of input list. The list iterated once
*
* Space Complexity: O(1) because no additional dynamic data structure was created
*/
// If there's only 1 price inside list, then you can't make a profit
if (prices.length <= 1) {
return 0;
}
int maxProfit = 0;
// Set 1st price as buying price and iterate list
int buyingPrice = prices[0];
for (int i = 1; i < prices.length; i++) {
// Set ith element as selling price
int sellingPrice = prices[i];
// If sellingPrice - buyingPrice >= 0, update maxProfit
// If not, then update buyingPrice to the newest smallest price
if (buyingPrice <= sellingPrice) {
maxProfit = Math.max(maxProfit, sellingPrice - buyingPrice);
}
else {
buyingPrice = prices[i];
}
}
return maxProfit;
}
public int solution1(int[] prices) {
int smallestPrice = Integer.MAX_VALUE;
int highestProfit = 0;
int todaysProfit = 0;
// Iterate array
for (int i = 0; i < prices.length; i++) {
// Update smallestPrice
if (prices[i] < smallestPrice) {
smallestPrice = prices[i];
}
// Calculate todaysProfit
todaysProfit = prices[i] - smallestPrice;
// If highestProfit is smaller than todaysProfit, update variable
if (highestProfit < todaysProfit) {
highestProfit = todaysProfit;
}
}
return highestProfit;
}
public int solution2(int[] prices) {
/*
OBJECTIVE: You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Time Complexity: O(n) where n = length of prices. A while-loop was created to iterate the loop once
Space Complexity: O(1) because no additional space was used
*/
// Get length of array
int n = prices.length;
// Create 2 pointers
int leftPtr = 0;
int rightPtr = 1;
// Create a variable to hold max profit
int maxProfit = 0;
// Iterate list
while (rightPtr < n) {
if (prices[leftPtr] < prices[rightPtr]) {
maxProfit = Math.max(maxProfit, prices[rightPtr] - prices[leftPtr]);
rightPtr++;
}
else {
leftPtr = rightPtr;
rightPtr++;
}
}
return maxProfit;
}
}