详细见: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))