best-time-to-buy-and-sell-stock-ii
/**
* @author gentleKay
* Say you have an array for which the i th 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).
*
* 假设您有一个数组,其中第i个元素是第一天给定股票的价格。
* 设计了一种求最大利润的算法。您可以完成任意多的交易
* (即,购买一份股票并多次出售一份股票)。
* 但是,您不能同时进行多个交易
* (即,您必须在再次购买之前出售股票)。
*/
/** * * @author gentleKay * Say you have an array for which the i th 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). * * 假设您有一个数组,其中第i个元素是第一天给定股票的价格。 * 设计了一种求最大利润的算法。您可以完成任意多的交易 * (即,购买一份股票并多次出售一份股票)。 * 但是,您不能同时进行多个交易 * (即,您必须在再次购买之前出售股票)。 */ public class Main06 { public static void main(String[] args) { int[] prices = {1,4,2}; System.out.println(Main06.maxProfit(prices)); } public static int maxProfit(int[] prices) { if (prices == null || prices.length < 2) { return 0; } int num = 0; for (int i=1;i<prices.length;i++) { if (prices[i] > prices[i-1]) { num = num + prices[i] - prices[i-1]; } } return num; } }