LeetCode122 Best Time to Buy and Sell Stock II

详细见:leetcode.com/problems/best-time-to-buy-and-sell-stock-ii


Java Solution: github

package leetcode;


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

public class P122_BestTimetoBuyandSellStockII {
	public static void main(String[] args) {
		Solution s = new Solution();
		System.out.println(s.maxProfit(new int[] {1, 2, 3, 4, 5}));
		System.out.println(s.maxProfit(new int[] {5, 4, 3, 2, 1}));
		System.out.println(s.maxProfit(new int[] {7, 1, 5, 3, 6, 4}));
	}
	/*
	 * 	AC
	 * 	2 ms
	 */
	static class Solution {
	    public int maxProfit(int[] prices) {
	    	if (prices == null) {
	    		return 0;
	    	}
	        int min = Integer.MAX_VALUE;
	        int ans = 0;
	        for (int i = 0; i < prices.length; i ++) {
	        	if (prices[i] > min) {
	        		ans += prices[i] - min;
	        		min = prices[i];
	        	} else {
	        		min = prices[i];
	        	}
	        }
	        return ans;
	    }
	}
}


C Solution: github

/*
    url: leetcode.com/problems/best-time-to-buy-and-sell-stock-ii
    AC 6ms 2.24%
*/

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int maxProfit(int* p, int pn) {
    int i = 0, a = 0;
    for (i = 1; i < pn; i ++) {
        if (p[i] > p[i-1]) {
            a += p[i] - p[i-1];
        }
    }
    return a;
}

int main() {
    int p[] = {1, 5, 2, 4};
    int pn = 4;
    printf("answer is %d\n", maxProfit(p, pn));
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/best-time-to-buy-and-sell-stock-ii
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年5月5日
    @details:    Solution:  56ms 39.52%
'''

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

if __name__ == "__main__":
    p = [1, 2, 3, 6, 4, 7]        
    print(Solution().maxProfit(p))





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值