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