LeetCode - Algorithms - 122. Best Time to Buy and Sell Stock II

自己已经意识到就是在输入数组里找递增子序列,但还是没想通。上网找点提示,参考了LeetCode – Best Time to Buy and Sell Stock II (Java),看了人家的,恍然大悟,不难,但就是想不到。

这系列 Best Time to Buy and Sell Stock 的题看来也是比较经典的

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
int diff = 0;
for(int i=1;i<prices.length;i++) {
diff = prices[i]-prices[i-1];
if (diff>0) {
profit+=diff;
}
}
return profit;
}
}

Submission Detail

  • 201 / 201 test cases passed.
  • Your runtime beats 99.86 % of java submissions.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
var profit = 0;
var diff = 0;
for(var i=1;i<prices.length;i++) {
diff = prices[i]-prices[i-1];
if (diff>0)
profit+=diff;
}
return profit;
};

Submission Detail

  • 201 / 201 test cases passed.
  • Your runtime beats 18.88 % of javascript submissions.