Maximum single sell profit - Java
Order O(n)
-------------------------------------------------------------------------------------------------------------
public class MaxSingleSellProfit {
public static Map<String,Double> getMaxSingleSellProfit(List<Double> weekValues){
Map<String,Double> result = new HashMap<String,Double>();
double maxValue = Double.MIN_VALUE;
for(int i=0; i< weekValues.size(); i++){
for (int j = 0; j < i; j++) {
double value = weekValues.get(i) - weekValues.get(j);
if(value > maxValue){
maxValue = value;
result.put("profit",maxValue);
result.put("buyDay", Double.valueOf(j));
result.put("sellDay",Double.valueOf(i));
}
}
}
return result;
}
public static void main(String[] args) {
Map<String,Double> result = getMaxSingleSellProfit(new ArrayList<Double>(){{
add(1.0);
add(100.0);
add(0.1);
add(1.5);
add(10.5);
add(40.0);
add(102.0);
}});
System.out.println("profit: "+result.get("profit"));
System.out.println("buyDay: "+result.get("buyDay").intValue());
System.out.println("sellDay: " +result.get("sellDay").intValue());
}
}
Output:
profit: 101.9
buyDay: 2
sellDay: 6
public class BuySellMaxProfit { public int max(int arr[]){ int maxProfit = arr[1] - arr[0]; int min = arr[0]; for(int i = 0; i < arr.length; i++){ if(arr[i] - min > maxProfit) maxProfit = arr[i] - min; if(arr[i] < min) min = arr[i]; } return maxProfit; } }
-------------------------------------------------------------------------------------------------------------
public class MaxSingleSellProfit {
public static Map<String,Double> getMaxSingleSellProfit(List<Double> weekValues){
Map<String,Double> result = new HashMap<String,Double>();
double maxValue = Double.MIN_VALUE;
for(int i=0; i< weekValues.size(); i++){
for (int j = 0; j < i; j++) {
double value = weekValues.get(i) - weekValues.get(j);
if(value > maxValue){
maxValue = value;
result.put("profit",maxValue);
result.put("buyDay", Double.valueOf(j));
result.put("sellDay",Double.valueOf(i));
}
}
}
return result;
}
public static void main(String[] args) {
Map<String,Double> result = getMaxSingleSellProfit(new ArrayList<Double>(){{
add(1.0);
add(100.0);
add(0.1);
add(1.5);
add(10.5);
add(40.0);
add(102.0);
}});
System.out.println("profit: "+result.get("profit"));
System.out.println("buyDay: "+result.get("buyDay").intValue());
System.out.println("sellDay: " +result.get("sellDay").intValue());
}
}
Output:
profit: 101.9
buyDay: 2
sellDay: 6
--------------------------------------------------------------------------------------------
Comments
Post a Comment