122. Best Time to Buy and Sell Stock II

题目:

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

Hide Tags
  Array Greedy  

链接: http://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

题解:

买卖股票,可以多次transactions。使用Greedy贪婪法。假如每天的股票价值比前一天高,则差值可以计算入总结果中。原理是类似1,2,3,4,5,除第一天外每天先卖后买的收益其实等于局部最小值1和局部最大值5之间的收益。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {

    public int maxProfit(int[] prices) {   //greedy

        if(prices == null || prices.length == 0)

            return 0;

        int result = 0;

            

        for(int i = 0; i < prices.length; i++){

            if(i > 0 && prices[i] - prices[i - 1] > 0)

                result += prices[i] - prices[i - 1];

        }

        

        return result;

    }

}

 

测试:

你可能感兴趣的:(time)