[LeetCode]Best Time to Buy and Sell Stock II

来源:互联网 发布:温和祛痘洗面奶知乎 编辑:程序博客网 时间:2024/06/16 11:05

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 {int sum = 0;    public int maxProfit(int[] prices) {    if(prices.length<1) return 0;    maxProfit(prices,0);    return sum;    }    private void maxProfit(int []prices,int start){    if(start>=prices.length-1) return;    int buy = prices[start];    int buyIndex = start;    for(int i=start+1;i<prices.length;i++){    if(prices[i]<=buy){    buy = prices[i];    buyIndex = i;    }else{    break;    }    }    int sell = prices[buyIndex];    int sellIndex = buyIndex;    for(int i=buyIndex+1;i<prices.length;i++){    if(prices[i]>=sell){    sell = prices[i];    sellIndex = i;    }else{    break;    }    }    sum += sell-buy;     maxProfit(prices,sellIndex+1);    }}




0 0