0X01 题目
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
0X02 题意
这个题目其实不难,想清楚后,至少能想起来一种比较简单的方法。
抛开题目的什么股票背景,大致意思就是求一个数组中a[j]-a[i]的最大值,j>i。
0X03 题解
1.解法一(Dante:Java)
第一反应想出来的方法,速度还可以,2ms。
两个指针:l指向左边的元素,r指向右边的元素,l永远在r的左边。max代表当前的最大值。
然后就是一个for循环,在每次循环中,如果发现prices[l] > prices[r],就将r的值赋给l。如果prices[l] <= prices[r],就判断一下当前prices[r] - prices[l]是否大于max,如果大于更新一下max的值。每次循环r++一下,就可以了。
public class Solution {
public int maxProfit(int[] ) {
int l = 0;
int r = 1;
int max = 0;
while (r < prices.length) {
if(prices[l] > prices[r]) {
l = r;
}else {
if(prices[r] - prices[l] > max) {
max = prices[r] - prices[l];
}
}
r++;
}
return max;
}
}
2016-08-01 16:36:18 hzct