leetcode_Best Time to Buy and Sell Stock II

来源:互联网 发布:redis mysql 编辑:程序博客网 时间:2024/06/05 19:40

描述:

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的利润相加即可,为何要这样出题?

代码:

public int maxProfit(int[] prices) {        if(prices==null)            return 0;        int len=prices.length;        if(len==0)            return 0;        int temp=0;        int maxProfit=0;        for(int i=1;i<len;i++)        {            temp=prices[i]-prices[i-1];        if(temp>0)                maxProfit+=temp;         }        return maxProfit;    }


0 0