【LeetCode】122.Best Time to Buy and Sell Stock II(Easy)解题报告

【LeetCode】122.Best Time to Buy and Sell Stock II(Easy)解题报告

题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
题目描述:

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

Solution:

//可以买卖多次,利用贪心策略
//time:O(n)
//space:O(1)
class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length<2) return 0;
        int profit = 0;
        for(int i=0 ; i1 ; i++){
            if(prices[i+1]>prices[i]){
                profit += prices[i+1] -prices[i];
            }
        }
        return profit;
    }
}

Date:2018年1月30日

你可能感兴趣的:(LeetCode,Array)