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).
public class Solution { public int maxProfit(int[] prices) { /* 题目:假设有一个数组,其中的第 i 个元素代表给定的第 i 天的股票价格。 设计一个算法找出最大的利润。你可以完成多个交易(如,买一和卖一股票 多次)。但是,你不能同时进行多个交易(如,你必须在新买入之前卖出)。 思路:可以理解成求任意多个二元序列之差 之和 的最大值,其中每对序列之差需为正数,对应的索引要减号之前的大于减号之后的。 如果是递增的序列对,就买入再卖出,求递增的所有序列的差和*/ int res=0; for(int i=0;i<prices.length-1;i++){ if(prices[i+1]>prices[i]){ res+=prices[i+1]-prices[i]; } } return res; } }