- Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
求最大子段和
f[j]存放i(0<=i<=j)到j的子段的最大子段和
初始化:f[0]=nums[0]
如果f[j-1]<=0,则f[j]=nums[j]
如果f[j-1]>0,f[j]=nums[j]+f[j-1]
同时,需要维护当前的最大字段和maxnum,及时进行修改
对空间复杂度进行优化,可以在原数组上存放最大子段和
nums[0]不修改
如果nums[j-1]<=0,则nums[j]没有必要修改
如果nums[j-1]>0,nums[j]=nums[j]+nums[j-1]
本题中,nums[0]=-2<0,
nums[1]=nums[1]=1>0,
nums[2]=nums[2]+nums[1]=-2<0,
nums[3]=nums[3]=4>0
nums[4]=nums[4]+nums[3]=3>0
......
- Climbing Stairs
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
爬楼梯问题
状态数组f[i]表示爬到第i层一共有多少种方式
爬到第i层有两种方式,一种是从i-1层爬上来,一种是从i-2层爬上来,
所以f[i]=f[i-1]+f[i-2]
初始化:f[0]=0,f[1]=1,f[2]=2
从第三层开始,可以按照转移方程推出来
- Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
维护的最大利润为max
对于第i天,记录前i-1天的最小值,如果prices[i]<min,则不能出售,更新min的值,
否则当天的利润=prices[i]-min,比较决定是否更新max
- Range Sum Query - Immutable
Given an integer array nums, find the sum of the elements between indices left and right inclusive, where (left <= right).
Implement the NumArray class:
NumArray(int[] nums) initializes the object with the integer array nums.
int sumRange(int left, int right) returns the sum of the elements of the nums array in the range [left, right] inclusive (i.e., sum(nums[left], nums[left + 1], … , nums[right])).
Example 1:
Input
[“NumArray”, “sumRange”, “sumRange”, “sumRange”]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output
[null, 1, -1, -3]
Explanation
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
本题首先需要关注类的实现。
因为题目要求多次调用sumRange函数,所以此函数的时间复杂度应该尽量小
状态表示为f[i]=前i个元素的和,所以sum(i,j)=f[j]-f[i-1]或sum(i,j)=f[j](j=0时)