Stock buy and sell GFG
package datastrusture;
public class Array {
// Efficient method
public static int max(int[] arr){
int n = arr.length;
int profit = 0;
for(int i = 1; i < n; i++){
if(arr[i] > arr[i - 1]) {
profit += arr[i] - arr[i - 1];
}
}
return profit;
}
//Stock buy and sell problem
public static int maxProfit(int[] arr, int start, int end){
if(end <= start){
return 0;
}
int profit = 0;
for(int i = start; i < end; i++){
for(int j = i + 1; j <= end; j++) {
if(arr[j] > arr[i]){
int curr_Profit = arr[j] - arr[i] + maxProfit(arr, start, i-1) + maxProfit(arr, j + 1, end);
profit = Math.max(profit, curr_Profit);
}
}
}
return profit;
}
public static void main(String[] args) {
// write your code here
int[] array = {1,5,3,8,12};
System.out.println(max(array));
}
}
Comments
Post a Comment