题意
给定一个数组来标识股票的价格,找到最能赚钱的买卖点,返回赚到的钱
我的思路
我的代码
穷举遍历法1
2
3
4
5
6
7
8
9
10
11public class Solution {
public int maxProfit(int[] prices) {
int max = 0;
for(int i=prices.length-1;i>=0;i--)
for(int j=i-1;j>=0;j--)
{
if((prices[i]-prices[j])>max) max = prices[i]-prices[j];
}
return max;
}
}
这么做是会超时的。
优化代码 把效率提升一个级别1
2
O(n^2) -> O(n)
从左开始找股票的最小值,并且遍历的时候拿去当前值
1 | public class Solution { |