以上的讨论是建立在 i > 0 的情况,我们还需要考虑动态规划的边界条件,即 i = 0 的情况:此时 nums}[0] 前面没有元素,本身可以构成一个长度为 1 的子数组,即 dp}[0] = \textit{nums}[0]。
又因为求解状态的过程只和前一个状态有关, 所以可以用「滚动数组」的方法来进行空间优化。
代码
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defmaxAscendingSum(self, nums: List[int]) -> int: ans = 0 i, n = 0, len(nums) while i < n: s = nums[i] i += 1 while i < n and nums[i] > nums[i - 1]: s += nums[i] i += 1 ans = max(ans, s) return ans
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intmaxAscendingSum(vector<int>& nums){ int res = 0; int l = 0; while (l < nums.size()) { int cursum = nums[l++]; while (l < nums.size() && nums[l] > nums[l - 1]) { cursum += nums[l++]; } res = max(res, cursum); } return res; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { publicintmaxAscendingSum(int[] nums) { intres=0; intl=0; while (l < nums.length) { intcursum= nums[l++]; while (l < nums.length && nums[l] > nums[l - 1]) { cursum += nums[l++]; } res = Math.max(res, cursum); } return res; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassSolution { publicintMaxAscendingSum(int[] nums) { int res = 0; int l = 0; while (l < nums.Length) { int cursum = nums[l++]; while (l < nums.Length && nums[l] > nums[l - 1]) { cursum += nums[l++]; } res = Math.Max(res, cursum); } return res; } }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#define MAX(a, b) ((a) > (b) ? (a) : (b))
intmaxAscendingSum(int* nums, int numsSize){ int res = 0; int l = 0; while (l < numsSize) { int cursum = nums[l++]; while (l < numsSize && nums[l] > nums[l - 1]) { cursum += nums[l++]; } res = MAX(res, cursum); } return res; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var maxAscendingSum = function(nums) { let res = 0; let l = 0; while (l < nums.length) { let cursum = nums[l++]; while (l < nums.length && nums[l] > nums[l - 1]) { cursum += nums[l++]; } res = Math.max(res, cursum); } return res; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12
funcmaxAscendingSum(nums []int) (ans int) { for i, n := 0, len(nums); i < n; { sum := nums[i] for i++; i < n && nums[i] > nums[i-1]; i++ { sum += nums[i] } if sum > ans { ans = sum } } return ans }