难度:easy
Java:
// //暴力法:超时了哈哈
// class Solution {
// public int maxProfit(int[] prices) {
// int length = prices.length;
// int ans = 0;
// for (int i = 0; i < length; i++) {
// for (int j = i; j < length; j++) {
// ans = Math.max(ans, prices[j] - prices[i]);
// }
// }
// return ans;
// }
// }
//贪心
class Solution {
public int maxProfit(int[] prices) {
int length = prices.length;
int ans = 0;
int low = prices[0];
//左边寻找最小的,遍历元素去减,取差值最大的
for (int i = 1; i < length; i++) {
low = Math.min(low, prices[i]);
ans = Math.max(ans, prices[i] - low);
}
return ans;
}
}
暴力法超时了哈哈,贪心的方法问题不大;
还有动态规划的方法;