题目编号
53 121
53. 最大子序和
解题思路
因为负数加负数更小,所以当目前总和为负数时,跟下一个负数只取一个较大的负数。
代码
| public int maxSubArray(int[] nums) { int[] dt = new int[nums.length]; dt[0] = nums[0]; int maxSum = nums[0]; for (int i = 1; i < nums.length; i++) { dt[i] = Math.max(dt[i - 1],0) + nums[i]; if (dt[i] > maxSum) { maxSum = dt[i]; } } return maxSum; }
|
121. 买卖股票的最佳时机
解题思路
因为只买卖一次,所以只要找到最大值前面的最小值就行了,每次模拟买入卖出情况,找出最大差值,解决问题。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public int maxProfit(int[] prices) { if (prices.length == 0) return 0; int buy = prices[0]; int profit = 0; int maxProfit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] < buy) { buy = prices[i]; } else if (prices[i] > buy) { profit = prices[i] - buy; if (profit > maxProfit) { maxProfit = profit; } } } return maxProfit; } }
|