122. 买卖股票的最佳时机 II
2018-04-01 本文已影响44人
第四单元
题目
假设有一个数组,它的第 i 个元素是一个给定的股票在第 i 天的价格。
设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。
思路
这一题不再限制买卖的次数。如输入[1,5,100],则:5-1=4,100-5=95。总收益为99
也就是说只要价格比前一天高就可以前一天买入、后一天卖出了。这个贪心算法真的
合理吗?是的,合理,因为确实找不出反例来。
代码
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] prices = new int[n];
for(int i = 0; i < n; i++)
prices[i] = scanner.nextInt();
Solution soluton = new Solution();
System.out.println(soluton.maxProfit(prices));
}
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int maxProfit = 0;
int len = prices.length;
for(int i = 1; i < len; i++) {
if(prices[i] - prices[i-1] > 0)
maxProfit += prices[i] - prices[i-1];
}
return maxProfit;
}
}