解法一:动态规划
class Solution {
public int maxProfit(int[] prices) {
int max = 0;
int min = Integer.MAX_VALUE;
for(int i=0;i<prices.length;i++){
min = Math.min(min,prices[i]);
max = Math.max(max,prices[i]-min);
}
return max;
}
}
- 时间复杂地:O(N)
- 空间复杂度:O(1)
https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/solution/mian-shi-ti-63-gu-piao-de-zui-da-li-run-dong-tai-2/
解法二:快慢指针
class Solution {
public int maxProfit(int[] prices) {
int left =0,right = left+1;
int max = 0;
while(right<prices.length){
if(prices[left]<prices[right]){
max = Math.max(prices[right]-prices[left],max);
right++;
}else{
left = right;
right++;
}
}
return max;
}
}
- 时间复杂度:O(N)
- 空间复杂度:O(1)