买卖股票的题,求最大利润。看上去十分高大上,答案让人吐血。原理很简单:买股票的人都喜欢抄底买涨到最高时候卖啊。
这道题不能想太多啊,不用关心什么时候买什么时候卖的问题:只要在涨,把利润加进去就好了。。。
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution:
public class Solution {
public int maxProfit(int[] prices) {
int max=0;
for(int i=0; i<prices.length-1;i++){
if(prices[i]<=prices[i+1]){
max+=prices[i+1]-prices[i];
}
}
return max;
}
}