Interview questions: the largest share of the profits
topic:
It is assumed that a stock's price in chronological order stored in an array, what's largest trading profits once the stock is likely to get much
Such as: a stock price for some time node} {9,11,8,5,7,12,16,14, if sold in May to buy 16, the maximum profit gains 11
Ideas:
Stock Trading profits from buying and selling shares of the difference, and can only sell after buying
If the bid and ask price of two digits of a number, the number of profit is the difference
The maximum profit is the difference between the maximum number of array all right
First, the solution can be violent - find all logarithm, differencing one by one, the time complexity of O (n)
two,
Defined maximum profit when selling price is the i-th array numbers may be obtained when the fixed selling price, the lower the price the greater the profit to buy
That is, if the array is scanned to the i-th digit, the minimum value of i-1 digits before long as we can remember is, you can calculate the maximum profit at the current selling price is likely to get
Code:
public class Q63 {
public static void main(String[] args) {
int[] a = new int[] {9,11,8,5,7,12,16,14};
int re = maxDiff(a);
System.out.println(re);
}
public static int maxDiff(int[] a) {
if(a.length<2) {
System.out.println("wrong input");
return 0;
}
int min = a[0];
int max = a[1]-a[0];
for(int i=1;i<a.length;i++) {
// 记录差值最大值
if(a[i]-min>max) {
max = a[i]-min;
}
// 记录最小值
if(a[i]<min) {
min = a[i];
}
}
return max;
}
}