Question:
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.
My code:
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2)
return 0;
int max = 0;
int i = 0;
while (i < prices.length) {
for (int j = i + 1; j < prices.length; j++) {
if (prices[j] <= prices[i]) {
i = j;
if (i == prices.length - 1)
return max;
else
break;
}
if (max < prices[j] - prices[i])
max = prices[j] - prices[i];
if (j == prices.length - 1)
return max;
}
}
return 0;
}
public static void main(String[] args) {
Solution test = new Solution();
int[] prices = {2, 1};
System.out.println(test.maxProfit(prices));
}
}
My test result:
這次作業卡了一段時間,主要是題目的意思沒有理解清楚。其實就是先要買,買了之后再賣。所以得在最低的時候買入,在最高的時候賣出,來賺取最多的錢。但是,又不是簡單的找最大值最小值問題。簡單的說,如果最小值出現在最大值之后,那么我買了最小值之后,無法賣出。因為數組是按時間排序的,最大值的那天已經過去了。
所以這道題目是簡單的動態規劃,以后我都會稱之為, DP。
**
總結: 我設置兩個指針。然后第二個指針開始往后遍歷。如果碰到的值比第一個指針大,則不斷刷新max值。當碰到的值比第一個指針小時,則第一個指針跳到第二個指針處。第二個指針開始從下一個值繼續遍歷。
以此循環。當然,比如輸入時 [2,1]時,我這個算法會有一些問題。需要在排除一些情況,然后就對了。
寫的還是不爽。
**
Anyway, Good luck, Richardo!
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0 || prices.length == 1)
return 0;
int[] max = new int[prices.length];
max[0] = 0;
int min = prices[0];
for (int i = 1; i < prices.length; i++) {
max[i] = Math.max(max[i - 1], prices[i] - min);
min = Math.min(min, prices[i]);
}
return max[max.length - 1];
}
}
** 沒想到 **
----- 09/23/2015 23:25
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1)
return 0;
int buy = prices[0];
int max = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < buy) {
buy = prices[i];
}
else {
max = Math.max(max, prices[i] - buy);
}
}
return max;
}
}
思路比較清晰。
感覺刷題這么久,進步還是有的。
Anyway, Good luck, Richardo!