leetcode121题目:
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
思路很简单,动态规划思想,直接上代码;
class Solution {
public int maxProfit(int[] prices) {
int min=Integer.MAX_VALUE;
int maxProfit=0;
for(int i=0;i<prices.length;i++){
if(prices[i]<min){
min=prices[i];
}else if(prices[i]-min>maxProfit){
maxProfit=prices[i]-min;
}
}
return maxProfit;
}
}
leetcode122
本来想想变形之后情况一下增加了好多种啊,不知如何下手;看了其他人的答案才恍然大悟,原来如此啊,怪不得被标记为easy。只要后面的值比前面的值大,那么久卖掉之前买的,这样总的值一直在增大,最后一定是最大的那个受益。
class Solution {
public int maxProfit(int[] prices) {
int total=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i+1]>prices[i]){
total+=prices[i+1]-prices[i];
}
}
return total;
}
}