题目要求:
求买卖股票一次能获得的最大利润。例如,输入{9,11,8,5,7,12,16,14},5的时候买入,16的时候卖出,则能获得最大利润11。
解题思路:
思路标签:
- 记录当前最小值和最大差值,并不断更新最大差值
public class Gupiao {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] data1 = new int[]{9,11,8,5,7,12,16,14};
int[] data2 = new int[]{9,8,7,6,5,4,3,1};
showMaxDiff(data1);
showMaxDiff(data2);
}
public static void showMaxDiff(int[] data){
if(data==null||data.length<2)
return ;
int min = data[0];
int index_min=0;
int maxDiff = data[1] - min;
int index_max=1;
if(data[1]<min)
{ min = data[1];index_min=1;}
for(int i=2;i<data.length;i++){
if(data[i]-min>maxDiff)
{ maxDiff = data[i]-min;index_max=i;}
if(data[i]<min)
{ min = data[i];index_min=i;}
}
System.out.println("买入点下标:"+index_min);
System.out.println("出售点下标:"+index_max);
System.out.println("最大收益值:"+maxDiff);
}
}