-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathStockBuyAndSell.java
More file actions
52 lines (45 loc) · 1.08 KB
/
StockBuyAndSell.java
File metadata and controls
52 lines (45 loc) · 1.08 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
47
48
49
50
51
52
/**
*
* Ashish Patel
* e: ashishsushilPatel@gmail.com
* w: https://ashish.me
*
*/
public class StockBuyAndSell {
static int func(int[] nums) {
int result = 0;
for(int i = 1; i < nums.length; i++){
if(nums[i-1] < nums[i]){
result += nums[i] - nums[i-1];
}
}
return result;
}
public static void main(String[] args) {
int[] nums = { 1, 5, 3, 8, 12 };
int result = func(nums);
System.out.println(result);
}
}
class StockBuyAndSell2 {
static int func(int[] nums, int start, int end) {
if (start >= end) {
return 0;
}
int result = 0;
for (int i = start; i < end; i++) {
for (int j = i + 1; j <= end; j++) {
if (nums[j] > nums[i]) {
int currentProfit = nums[j] - nums[i] + func(nums, start, i - 1) + func(nums, j + 1, end);
result = Math.max(result, currentProfit);
}
}
}
return result;
}
public static void main(String[] args) {
int[] nums = { 1, 5, 3, 8, 12 };
int result = func(nums, 0, nums.length - 1);
System.out.println(result);
}
}