LeetCode-探索-初级算法-数组-2. 买卖股票的最佳时机 II(个人做题记录,不是习题讲解)
程序员文章站
2024-03-23 10:40:28
...
LeetCode-探索-初级算法-数组-2. 买卖股票的最佳时机 II(个人做题记录,不是习题讲解)
- 语言:java
- 执行时间:1ms
- 个人思路:如果当前值>之前值,则设置记录当前值为最大值max;如果当前值<=之前值,则改变之前值坐标;改变之前值做标签,当前值要是<max,则说明可以在这之前结算前面进行的一笔买卖;
class Solution {
public int maxProfit(int[] prices) {
int pre = 0;
int total = 0;
int max = 0;
int i = 1;
int len = prices.length;
for(;i<len;++i){
if(prices[i]<=prices[pre]||prices[i]<max){
if(prices[i]<max){
total += max-prices[pre];
max = 0;
}
pre = i;
}else{
max = prices[i];
}
}
if(max!=0)
total += max-prices[pre];
return total;
}
}
-
语言:java
-
执行时间:1ms
-
个人思路:参考了网友的1ms代码,其思路即记录每两次坐标的差价,要是>0,则这两笔进行买卖,计入盈利中。
-
参考代码:
class Solution { public int maxProfit(int[] prices) { int max = 0; for(int i = 1;i <= prices.length - 1;i++){ int diff = (prices[i] - prices[i-1]); if(diff > 0){ max += diff; } } return max; } }
class Solution {
public int maxProfit(int[] prices) {
int i =1;
int len = prices.length;
int sum = 0;
int diff = 0;
for(;i<len;++i){
diff = prices[i] - prices[i-1];
if(diff>0)
sum += diff;
}
return sum;
}
}
下一篇: HTML5 WebSocket