Question:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
My code:
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2)
return 0;
boolean isInMode = false;
int i = 0;
int max = 0;
int tempMax = 0;
while (i < prices.length) {
for (int j = i + 1; j < prices.length; j++) {
if (prices[j] <= prices[i] && !isInMode) {
i = j;
tempMax += max;
max = 0;
if (i == prices.length - 1)
return tempMax;
else
break;
}
else if (prices[j] > prices[i] || isInMode) {
if (prices[j] < prices[j - 1] && isInMode) {
isInMode = false;
i = j;
tempMax += max;
max = 0;
if (i == prices.length - 1)
return tempMax;
else
break;
}
if (prices[j] > prices[i]) {
if (j - i == 1)
isInMode = true;
if (max < prices[j] - prices[i])
max = prices[j] - prices[i];
if (j == prices.length - 1)
return max + tempMax;
}
}
}
}
return 0;
}
public static void main(String[] args) {
Solution test = new Solution();
int[] prices = {6, 1, 3, 2, 4, 7};
System.out.println(test.maxProfit(prices));
}
}
My test result:
這次比較難。需要多次算盈利。然后又是寫了好多if語句。這是不好的習慣。寫的也很痛苦。
這個程序應該分為三種狀態。
然后我根據三種狀態來構造程序。實現要求。
之后我看了別人的思路,發現完全沒有這么復雜。
這也是我的一個問題,總是把問題想復雜,站的角度不對,導致寫的代碼很復雜。
記住, code is simple. The world is simple.
怎么樣的思路呢?
就是數組中后面的減前面的,如果小于0,就拋棄,繼續遍歷。
如果大于0,則將差值加入。
具體實現,我借了別人的圖。
**
總結:還是那個說法, 寫代碼前先仔細想想,到底該用什么思路去解決。這次一開始是為了偷懶,所以想直接改改之前的代碼。所以思路被局限在了上一道題目,導致這道題目越想越復雜。
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1)
return 0;
int max = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] >= prices[i - 1]) {
max += prices[i] - prices[i - 1];
}
}
return max;
}
}
和以前的代碼一比,感覺好清爽。。。
Anyway, Good luck, Richardo!
這道題目已經做爛了。。。
Anyway, Good luck, Richardo! --- 08/11/2016