【leetcode】122. best time to buy and sell stock ii

Description

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).

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
public int (int[] nums) {
int len = nums.length;
int sum = 0;
if (len == 0 || len == 1) {
return sum;
}
for (int i = 1; i < len; i++) {
if (nums[i] > nums[i - 1]) {
sum += nums[i] - nums[i - 1];
}
}
return sum;
}

Result

AC

Analyse

这个方法比较简单,复杂度是O(n),其他的更好的方法目前也没看到。