题目:假设你有一个数组,其中第i 个元素是股票在第i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
if(prices == null || prices.length == 0) return 0;
int maxProfit = 0 ,buy = prices[0];
for(int i=0;i<prices.length;i++){
buy = Math.min(buy,prices[i]); //挑选出整个数组中比buy的值更小的值
maxProfit = Math.max(maxProfit,prices[i]-buy); //挑选出数组中-buy的差值最大的值
}
return maxProfit;
}
}
升级:股票有多次买入和卖出的机会,求最大收益
解答:不用考虑到底那一天买进,那一天卖出,只要今天的股票价格大于昨天的我就卖出,然后最后有一个总的收益值。
例如:2,5,3,8,9,7
1.赋值一个变量:total(股票的最大收益值)=0,2<5,卖出:total+=5-2=3;
2.5>3.既不买进,也不卖出。
3.3<8,卖出,total+= 3+(8-3) = 8;
4.8<9卖出,total+=8+(9-8)=9;
5.9>7.既不买进,也不卖出。所以最后的最大收益为9
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
int total = 0;
for(int i=0;i<prices.length;i++){
if(prices[i]<prices[i+1]){
total += prices[i+1] - prices[i];
}
}
return total;
}
}