[leetcode]Best Time to Buy and Sell Stock II

一开始没理解对题意,估计是理解成III那道题的样子了。理解对了以后发现挺简单的。但看了参考之后发现它的解法更简洁优美,就直接照着来了。

public class Solution {

    public int maxProfit(int[] prices) {

        // Start typing your Java solution below

        // DO NOT write main() function

        int total = 0;

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

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

        		total += (prices[i] - prices[i-1]);

        	}

        }

        return total;

    }

}

第二刷:

class Solution {

public:

    int maxProfit(vector<int> &prices) {

        int m = 0;

        if (prices.size() == 0)

            return m;

        for (int i = 1; i < prices.size(); i++) {

            if (prices[i] >= prices[i - 1]) {

                m += (prices[i] - prices[i - 1]);

            }   

        }

        return m;

    }

};

  

你可能感兴趣的:(LeetCode)