L7_数组
Median of a array
个数奇数时候取中间那个数
个数偶数取中间两数的平均
Maximum Subarray I 和 buy and sell stock
每次loop时第二行用来保存前面最小的Price或者最小的minSum,这样可以省一次loop
然后当前的price减去min得到的数字max
Maximum Subarray III
比较 Best Time to Buy and Sell Stock IV
也是维护global和local, 因为sum是连续相加数组,这里价格买入卖出有加减,所以逻辑有差别。k>n/2之后直接退化为贪心算法
基本上就是i个数j次数,每次不是i-1就是j-1。j-1就是决定当前这次怎么处理:数组里就是决定属于前堆还是当前堆,股票里就是当前卖不卖,要用当前减去之前某次。和Best Time to Buy and Sell Stock III 中left[i] = Math.max(prices[i] - minPrice, left[i-1]);
不一样stock中价格相减,此处数字叠加。
股票问题
Therefore our definition ofT[i][k]
should really be split into two:T[i][k][0]
andT[i][k][1]
, where theformerdenotes the maximum profit at the end of thei-th
day with at mostk
transactions and with0
stock in our hand AFTER taking the action, while thelatterdenotes the maximum profit at the end of thei-th
day with at mostk
transactions and with1
stock in our hand AFTER taking the action. Now the base cases and the recurrence relations can be written as:
For the base cases,T[-1][k][0] = T[i][0][0] = 0
has the same meaning as before whileT[-1][k][1] = T[i][0][1] = -Infinity
emphasizes the fact that it is impossible for us to have1
stock in hand if there is no stock available or no transactions are allowed.
总结用法:
可以左边遍历再右边遍历 Shortest Distance to a Character(必须数组因为返回数组),Longest Mountain in Array(可以优化数组为数字因为返回最大值)
矩阵遍历
如果行数可以直接计算,列数需要用数组,因为遍历的方向性
bomb enemy
Last updated