-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBestTimeToBuyAndSellStocksII.java
More file actions
46 lines (38 loc) · 1.12 KB
/
BestTimeToBuyAndSellStocksII.java
File metadata and controls
46 lines (38 loc) · 1.12 KB
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
// Optimised Solution TC: O(n) SC: O(1)
/*
Runtime: 1 ms, faster than 97.51% of Java online submissions for Best Time to Buy and Sell Stock II.
Memory Usage: 44.5 MB, less than 39.82% of Java online submissions for Best Time to Buy and Sell Stock II.
*/
class Solution {
public int maxProfit(int[] prices) {
int maxprofit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1])
maxprofit += prices[i] - prices[i - 1];
}
return maxprofit;
}
}
// Brute Force Solution TC: O(n) SC: O(1)
class Solution {
public int maxProfit(int[] a){
int min = a[0];
int sum = 0;
int profit = 0;
int diff = 0;
for(int i=1; i<a.length; i++){
if(min > a[i]){
min = a[i];
}
diff = a[i] - min;
if(sum < diff){
sum = diff;
min = a[i];
// profit = profit + diff;
}
profit = profit + sum;
sum=0;
}
return profit;
}
}