Leetcode ☞ 122. Best Time to Buy and Sell Stock II

来源:互联网 发布:老男孩linux运维笔记 编辑:程序博客网 时间:2024/06/11 14:33

网址https://leetcode.com/problems/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).


我的AC:

int maxProfit(int* prices, int pricesSize) {    int ans = 0;    for (int i = pricesSize - 1; i >0; i-- ){        if (prices[i] > prices[i - 1])            ans += (prices[i] - prices[i - 1]);    }    return ans;}


分析:

只要后面的数比前面的大,就算获利,管它的~


python一行搞定:

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        return sum(max(prices[i+1] - prices[i], 0) for i in range(len(prices) - 1) )









0 0
原创粉丝点击