LeetCode - 122. Best Time to Buy and Sell Stock II

来源:互联网 发布:ubuntu空闲分区不显示 编辑:程序博客网 时间:2024/05/05 10:01

相比于上一道题目Best Time to Buy and Sell Stock,这道题目可以交易多次,那么在从前向后扫描数组的过程中,只要后面一天的股票价格高于当今的股票价格,就进行股票的交易,相当于是使用了贪心的思想,代码如下:

public class Solution {    public int maxProfit(int[] prices) {        if(prices == null || prices.length == 0) return 0;      // corner case                int result = 0;        for(int i = 0; i < prices.length - 1; i++){            if(prices[i + 1] > prices[i]){                result += prices[i + 1] - prices[i];            }        }                return result;    }}


0 0
原创粉丝点击