Best Time to Buy and Sell Stock II

来源:互联网 发布:写剧本的软件 编辑:程序博客网 时间:2024/06/08 02:47

思路源自小莹子点击打开链接,

总是找到一个递减序列的最底部,然后找到递增序列的最高点,求差值。

public class Solution {    public int maxProfit(int[] prices) {        if (prices == null || prices.length == 0) {            return 0;        }        int total = 0, i = 0;        while (i < prices.length - 1) {            int buy = 0, sell = 0;            while (i < prices.length - 1 && prices[i] >= prices[i + 1]) {                i++;            }            buy = i;            while (i < prices.length - 1 && prices[i] <= prices[i + 1]) {                i++;            }            sell = i;            total = total + prices[sell] - prices[buy];            i++;        }                return total;    }}

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).


0 0